我有以下的React组件:
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
- 有什么想法这个代码有什么问题吗?
this.onSubmit.bind(this)
的意思是绑定当前的this
到onSubmit
方法上。 - zerkmse.target.value
怎么样? - omarjmhonClick={this.onSubmit.bind(this)}
)时,您需要将onSubmit
方法绑定到提交按钮(DOM 元素)。如果您想访问表单中标题输入的值,可以使用onSubmit(event) { const title = event.target.elements.title.value; }
。 - tim-montague