0
我試圖在用戶輸入後更改狀態更改時更改輸入字段的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並像那樣改變它。
有沒有更好的方法來做到這一點,我不知道?
所以基本上創建只是輸入一個單獨的組件? –
不,你不需要。我已經添加了您可以對您的代碼進行修改以使其正常工作。 – Pineda
唯一的區別是,在我對這個特定問題的輸入中,我不是直接在這個特定輸入中輸入標題,而是另一個輸入。但你的解決方案工作。我所要做的就是去掉'defaultValue'道具,添加一個'onChange'道具並讓onChange通過設置狀態來處理標題變化,而不是通過vanilla JS直接調用DOM。 –