Javascript 使用状态更新输入文本值并使其可变
我想使用state和ReactJavascript 使用状态更新输入文本值并使其可变,javascript,reactjs,typescript,Javascript,Reactjs,Typescript,我想使用state和Reactvalue属性更改输入文本值,并使字段可编辑 我的组件的构造函数: constructor(props) { super(props); // States this.state = { value: this.props.object.subtext }; this._handleChange = this._handleChange.bind(this); } 我的render()函数: return
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() {
if (this.state.value !== this.props.object.subtext) {
this.setState({value: this.props.object.subtext});
}
}
_handleChange(e) {
this.props.object.subtext = e.target.value;
this.componentDidUpdate(); // not sure it's right or not
}
对于\u handleChange(e)
功能:
return (
<input
type={this.props.object.type}
value={this.props.object.subtext}
onChange={this._handleChange}
/>
);
componentDidUpdate() {
if (this.state.value !== this.props.object.subtext) {
this.setState({value: this.props.object.subtext});
}
}
_handleChange(e) {
this.props.object.subtext = e.target.value;
this.componentDidUpdate(); // not sure it's right or not
}
代码运行良好,但我有点不确定这是不是最佳实践,因为我在事件处理程序函数中手动调用了this.componentdiddupdate()
我这样做是为了修复我以前的错误,即当状态更改时,输入组件的值不会更新
我想知道我所做的是否正确,任何评论或回答都将不胜感激。正如您怀疑的那样,调用
componentdiddupdate
是个坏主意。您可以在\u handleChange
中更改状态,并删除组件diddupdate
调用。您可以在\u handleChange
中设置状态。但是,您需要为本地状态绑定到this.state.value
,而不是this.props.object.subtext
。注意以下几点
constructor(props) {
super(props);
this.state = {
value: this.props.object.subtext
};
}
_handleChange(e) {
this.setState({
value: e.target.value
});
}
render() {
return (
<input
type={this.props.object.type}
value={this.state.value}
onChange={this._handleChange.bind(this)}
/>
);
}
构造函数(道具){
超级(道具);
此.state={
值:this.props.object.subtext
};
}
_手变(e){
这是我的国家({
价值:即目标价值
});
}
render(){
返回(
);
}
或者,如果您正在寻找一个没有本地州的props
唯一解决方案,我建议
看看。不,自己调用生命周期函数不是一个好做法
相反,您可以修改您的状态道具,如
constructor(props) {
super(props);
// States
this.state = {
value: this.props.object.subtext
};
this._handleChange = this._handleChange.bind(this);
}
componentWillReceiveProps(nextProps) {
if (this.props.object.subtext !== nextProps.object.subtext) {
this.setState({value: nextProps.object.subtext});
}
}
_handleChange(e) {
//cal a parent compoent function
this.props.changeProps(e.target.value);
}
请勿更改组件内部的道具_handleChange应将值传递给父组件Callback我尝试了此操作,但在状态更改时输入文本值未更新。应可以正常工作。诚然,虽然不是TypeScript或类,但这里有一个完全复制的工作示例-this.props.changeProps()
从何而来?在父组件中定义一个函数changeProps,它更改传递给子对象的值object.subtext,并将此函数传递给子函数,如{this.changeProps(val)}/>,输入组件现在变为不可变。这是正确的方法,并且This.props.object.subtext=e.target.value代码>,是错误的,this.props.object.subtext=e.target.value代码>使它成为不可变的?