在我的组件中,我试图调用组件的 handleChange 和 handleSubmit 函数
如果我像表单示例一样呈现,
<form onSubmit={this.handleSubmit}>
<input type="text" value={this.state.value} onChange={this.handleChange} placeholder="Enter new title"/>
<input type="submit" value="Submit" />
</form>
在 onChange() 中,this不会绑定到组件,也不能调用this.setState,所以我用 onChange={() => this.handleChange} 绑定。
for onSubmit(),我有同样的绑定问题,但是当我绑定它时,没有调用处理程序,并重新加载页面。提交时绑定到组件的正确方法是什么?
TIA
完整示例:
class CbList extends React.Component {
constructor() {
super();
this.state = {
newTitle: '',
list: []
};
}
handleChange(event) {
this.setState(Object.assign({},
this.state,
{ newTitle: event.target.value }));
}
handleSubmit(event) {
this.addBlock(this.state.newTitle);
event.preventDefault();
return false;
}
render() {
return (
<div className="cb-list">
<div>
<form onSubmit={() => this.handleSubmit}>
<input type="text" value={this.state.value} onChange={() => this.handleChange}
placeholder="Enter new title"/>
<input type="submit" value="Submit" />
</form>
</div>
</div>
);
}
addBlock(title) {
let updatedList = this.state.list.concat({ title: title });
this.setState({ list: updatedList })
}
};
$(function() {
ReactDOM.render(<CbList/>, $('#home').get(0));
});