我对React很陌生,在完成一些教程之后,我尝试使用下面的代码。
我制作了一个组件,并从商店传递了道具,然后componentWillMount为组件创建了新状态。到目前为止,渲染效果还不错。
componentWillMount
接下来,我state将输入框的值绑定到其中,并且还具有onChange侦听器。不过,我无法在该字段中更改自己的值。
state
onChange
因为,我从角的背景是,我假设输入的值绑定状态像下面会自动更新属性name的state对象。我在这里错了吗?
name
componentWillMount(){ this.setState({ updatable : false, name : this.props.name, status : this.props.status }); } //relevant DOM from component's render function <input className="form-control" type="text" value={this.state.name} id={'todoName' + this.props.id} onChange={this.onTodoChange.bind(this)}/> onTodoChange(){ console.log(this); //consoling 'this' here, shows old values only. //not sure how and even if I need to update state here. // Do I need to pass new state to this function from DOM //TODO: send new data to store }
我的onTodoChange功能控制台的值与this初始化时的状态值相同。如何通过在输入框中键入内容来更改状态,以便可以将其发送到商店。
onTodoChange
this
与Angular不同,在React.js中,您需要手动更新状态。您可以执行以下操作:
<input className="form-control" type="text" value={this.state.name} id={'todoName' + this.props.id} onChange={e => this.onTodoChange(e.target.value)} />
然后在函数中:
onTodoChange(value){ this.setState({ name: value }); }
另外,您可以在Component的构造函数中设置初始状态:
constructor (props) { super(props); this.state = { updatable: false, name: props.name, status: props.status }; }