【发布时间】:2016-11-25 17:19:11
【问题描述】:
当用户输入后状态发生变化时,我试图找到一种更 React 类型的方式来更改输入字段。这是我当前的设置,但我正在寻找一种方法来做到这一点,而无需在 componentWillReceiveProps 方法中向 DOM 发出信号:
export default class Example extends React.Component {
constructor(props){
super(props);
this.state = {title: props.arr.question};
};
componentWillReceiveProps(nextProps){
if(nextProps.arr.question !== this.state.title){
let id = "question" + this.props.arr.key;
document.getElementById(id).value = nextProps.arr.question;
this.setState({title: nextProps.arr.question});
}
}
render(){
return(<div>
<input type="text" id={"question" + this.props.arr.key} defaultValue={this.state.title} placeholder="Enter your title."/>
</div>
)
}
}
我的假设是,当状态发生变化时,我也会看到输入发生变化。事实上,出于某种原因,除了输入字段之外的任何元素都会发生这种情况。所以我发现的唯一想法是在 componentWillReceiveProps 方法中引用 DOM 并像这样进行更改。
有没有我不知道的更好的方法来做到这一点?
【问题讨论】:
标签: reactjs