Javascript 在React JS中处理两个有状态组件中的onchange
我是一个新手,在处理和调用onChange事件时感到困惑 现在,我有两个组件:-Javascript 在React JS中处理两个有状态组件中的onchange,javascript,reactjs,Javascript,Reactjs,我是一个新手,在处理和调用onChange事件时感到困惑 现在,我有两个组件:- 1. Parent component - updateField = e => { console.log("update field e called"); this.setState({ value: e.target.value }); }; <InputTypeahead value={thi
1. Parent component -
updateField = e => {
console.log("update field e called");
this.setState({
value: e.target.value
});
};
<InputTypeahead value={this.state.value} label="Email" onChange={this.updateField} typeaheadItems={this.emailAdressess} /
非常感谢您的帮助。谢谢。从16.3.0版开始,您可以使用getDerivedStateFromProps方法根据props更新状态,如
class InputTypeahead extends React.Component {
state = {
value: ''
}
static getDerivedStateFromProps(nextProps, prevState) {
if(nextProps.value !== prevState.value) {
return { value: nextProps.value};
}
return null;
}
}
根据:
getDerivedStateFromProps
在组件启动后调用
实例化以及收到新道具时。它应该会回来
要更新状态的对象,或null以指示新道具
不需要任何状态更新
在v16.3.0之前,您将使用构造函数和组件WillReceiveProps,如
class InputTypeahead extends React.Component {
constructor(props) {
super(props);
this.state = {
value: props.value
}
}
componentWillReceiveProps(nextProps) {
if(nextProps.value !== this.props.value) {
this.setState({ value: nextProps.value});
}
}
}
谢谢shubham。但在项目中,我们使用的是16.2。你能指导吗?更新了答案,请检查谢谢shubham。我忽略了生命周期挂钩。哈哈:)@Pourushinghgaur,生命周期挂钩是React中最好的东西,最好知道在什么时候调用哪个生命周期。无论如何,我很高兴能帮上忙。我一定会提高我的知识。我想了解一件事,在我的父组件中——我调用更改——捕获用户输入的计算。在子组件中,我需要调用child的onchange,以便我可以设置状态。
class InputTypeahead extends React.Component {
constructor(props) {
super(props);
this.state = {
value: props.value
}
}
componentWillReceiveProps(nextProps) {
if(nextProps.value !== this.props.value) {
this.setState({ value: nextProps.value});
}
}
}