如何使用 ReactJS 获取输入字段的值? [英] How to get the value of an input field using ReactJS?
本文介绍了如何使用 ReactJS 获取输入字段的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下 React 组件:
I have the following React component:
export default class MyComponent extends React.Component {
onSubmit(e) {
e.preventDefault();
var title = this.title;
console.log(title);
}
render(){
return (
...
<form className="form-horizontal">
...
<input type="text" className="form-control" ref={(c) => this.title = c} name="title" />
...
</form>
...
<button type="button" onClick={this.onSubmit} className="btn">Save</button>
...
);
}
};
控制台给我 undefined
- 知道这段代码有什么问题吗?
The console is giving me undefined
- any ideas what's wrong with this code?
推荐答案
你应该在 MyComponent extends React.Component 类下使用构造函数
You should use constructor under the class MyComponent extends React.Component
constructor(props){
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
然后你会得到title的结果
Then you will get the result of title
这篇关于如何使用 ReactJS 获取输入字段的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文