[英]Why isn't my input value updating with React?
我的組件中有以下代碼。 當我更新某些東西時它會被調用,從而替換 UI 中的一堆東西。 一切都在更新,除了用戶看到的輸入值。
let input = {
id: 'discount-' + geo + '-' + segment,
value: percentage,
disabled: applyToAll,
placeholder: '0.00'
};
cells.push(
<td key={'cell-' + geo + '-' + segment} className="discount-segment cfix">
<Text {...input} />
</td>
);
這是<Text>
返回的內容,為了清楚起見,刪除了一些內容
return (
<div className={containerClasses.join(' ')} id={'field-container-' + id}>
{label}
<input
autoComplete="off"
type="text"
id={id}
ref="input"
{...extraProps}
name={id}
className={classes.join(' ')}
defaultValue={this.props.value}
onChange={this.props.onChange}
/>
</div>
);
一切都很好。 假設開始時percentage
值為5
,它將在字段中顯示5
。 然后我做一些其他事情,將percentage
更新為 50。(控制台日志將在重新渲染時顯示正確的數字)。 然而,該值仍然只在 UI 中顯示5
。 我在輸入字段上使用defaultValue
,但我認為隨着整個事物從父級重新呈現,這應該會發生變化。
編輯更新<Text>
以設置value
而不是defaultValue
。 但是,當用戶鍵入時,我需要使用state
來更新值。 然后當我重新渲染時,我發送了具有適當價值的新道具,但道具當然沒有更新。 Catch-22 對我來說。
您需要執行幾個步驟:
value
和onChange
道具,不要使用defaultValue
因此,例如:
const MyComponent = React.createClass({
propTypes: {
defaultInputValue: React.PropTypes.string
},
getInitialState() {
return {
inputValue: this.props.defaultInputValue
};
},
componentWillReceiveProps(nextProps) {
if (nextProps.defaultInputValue !== this.props.inputValue) {
//Forcibly overwrite input value to new default if the default ever changes
this.setState({inputValue: nextProps.defaultInputValue});
}
},
render() {
return <input type="text"
value={this.state.inputValue}
onChange={e => this.setState({inputValue: e.target.value})} />;
}
});
一般來說,從 props 初始化狀態是一個禁忌。 如果我在代碼審查中看到這種情況,我可能會有點畏縮,因為可能有一些可以簡化的行為。
你也可以這樣做:
<input value={this.state.inputValue || this.props.defaultInputValue} />
這樣,如果您清除輸入,輸入的值將恢復為 prop 值。 在這種情況下,您不必用新道具強行覆蓋狀態。
我們可以這樣做。我們必須使用 onChnage() 事件。
<input placeholder="as_you_want"
value={this.state.as_your_state}
onChange={e => {
this.setState({ as_your_state: e.target.value });
this.value = this.state.as_your_state;
}}
/>
希望這有效。
componentWillReceiveProps
是現在已經過時,甚至它的后繼getDerivedStateFromProps
被建議反對。 為了圓“我需要管理一個文本輸入的狀態(state),但我也需要它在我重新渲染時更新它的初始值(props)”,React博客推薦在props中使用一個key . 當 key 發生變化時,組件會重新掛載,props 可以重新初始化 state。
為了在輸入發生任何變化時積極強制組件刷新,我會使用
<Text {...input} key={JSON.stringify(input)}/>
然后你可以像正常的受控形式一樣使用value={this.state.value}
,但是你可以設置this.state.value = props.value
並且它每次都會改變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.