我很難與組件,我希望你們會幫助我。 所以我創建了一個自定義組件,它返回用戶在輸入中鍵入的內容的格式化值(如果用戶鍵入'1999-9-9',則返回'1999-09-09 00:00'),並且值被分配給父級的狀態(handleCustomInputValueChange)。 現在..問題是,如果我點擊'數字'類型,並用隨機字符填充輸入,保存它並去'datetime',輸入保持不變,它不會重置或不'從道具獲取數據。它具有「數字」中的舊值。 使用componentWillReceiveProps()方法,在許多情況下將是這個問題的答案,但不是在這裏,因爲我只想將數據發送給父級。我不需要將這些數據發送回我的'CustomInput'。反應 - 重置組件輸入
父組件:
handleCustomInputValueChange(changeEvent) {
this.setState({value: changeEvent});
}
...
switch(type) {
case 'NUMERIC':
return <CustomInput data={value} type="numeric" callbackParent={handleCustomInputValueChange} />
break;
case 'DATETIME':
return <CustomInput data={value} type="datetime" callbackParent={handleCustomInputValueChange} />
break;
}
子組件
export default class CustomInput extends Component {
constructor(props) {
super();
this.state = {
value: props.data || ''
}
}
handleChange(event) {
/* formatting data */
callbackParent(formattedData);
}
render() {
return <input type="text" onChange={this.handleChange} value={this.state.value} />;
}
}
所以..有什麼辦法切換到另一種類型後,輸入復位?
謝謝!
你可以使用'onBlur'事件重置輸入。輸入鬆散焦點時,將會觸發'onBlur'事件。 – Valour