首页 > 解决方案 > 根据反应中的道具或状态更改输入

问题描述

我有一个包含输入框的组件。该组件将接收一个道具来启动输入框的值。

class MyInput extends React.Component{
 constructor(props){
    super(props);
    this.state = {
        phrase : this.props.phrase
    }
 }
 onChange(e) {
    this.setState({
      phrase: e.target.value
    })
 } 
 render(){
   return <input value={this.state.phrase}
           onChange={this.onChange.bind(this)}/>
  }
}

现在,我希望能够通过更改道具来更改输入框的值,但是由于我需要输入与状态同步,所以我不知道该怎么做。

标签: reactjsreact-props

解决方案


class MyInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      phrase: props.phrase
    };
  }
  onChange = (e) => {
    this.setState({
      phrase: e.target.value
    });
  }
  componentDidUpdate(prevProps) {
    if (this.props.phrase != prevProps.phrase) {
      this.setState({ phrase: this.props.phrase });
    }
  }
  render() {
    return <input value={this.state.phrase} onChange={this.onChange} />;
  }
}

推荐阅读