【发布时间】:2017-05-19 15:49:41
【问题描述】:
我想使用 state 和 React value 属性更改输入文本值,并使该字段可编辑。
我的组件的构造函数:
constructor(props) {
super(props);
// States
this.state = {
value: this.props.object.subtext
};
this._handleChange = this._handleChange.bind(this);
}
我的render() 功能:
return (
<input
type={this.props.object.type}
value={this.props.object.subtext}
onChange={this._handleChange}
/>
);
componentDidUpdate()函数:
componentDidUpdate() {
if (this.state.value !== this.props.object.subtext) {
this.setState({value: this.props.object.subtext});
}
}
对于_handleChange(e) 函数:
_handleChange(e) {
this.props.object.subtext = e.target.value;
this.componentDidUpdate(); // not sure it's right or not
}
代码运行良好,但我有点不确定这是不是最佳实践,因为我在事件处理函数中手动调用了this.componentDidUpdate()。
我这样做是为了修复我之前的错误,即当状态改变时输入组件的值不会被更新。
我想知道我所做的是否正确,任何 cmets 或答案将不胜感激。
【问题讨论】:
-
不要更改组件内部的道具。 _handleChange 应该将值传递给父组件回调
标签: javascript reactjs typescript