reactjs - 根据反应中的道具或状态更改输入
问题描述
我有一个包含输入框的组件。该组件将接收一个道具来启动输入框的值。
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)}/>
}
}
现在,我希望能够通过更改道具来更改输入框的值,但是由于我需要输入与状态同步,所以我不知道该怎么做。
解决方案
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} />;
}
}
推荐阅读
- python - 直接使用 QtMultimedia.QAudioOutput 播放 gtts 缓冲区
- symfony - Symfony服务收集不同方法的区别
- java - 如何从 Apache Commons Math - Java 库中找到伪逆
- flutter - 如何在颤振应用程序中将小部件覆盖在 MaterialApp 导航器之上?
- angular - 为什么我的变量没有在 Typescript 中被分配为数组?
- python - 如何在 python 中选择与特定文件夹相关的文件?
- goto - 如何在没有 goto 的情况下基本编程,但计算时间也不短
- java - 我应该如何在 springboot async 中使用 CompletableFuture 作为 void 方法
- java - 在线程“主”org.openqa.selenium.WebDriverException 中获取异常:无法解析远程响应:需要授权
- php - 在 Shopify 资产 API Laravel 中获取空白值以检索主题的单个资产