當您將this.props.user.first_name
分配給value
屬性時,並不是輸入字段變爲只讀,而是您從不處理該值發生更改時發生的情況。 React只是用每次直接分配給它的值重新渲染它。
如果您希望使字段可編輯且具有默認的用戶名值,您應該維護並瞭解輸入的狀態。
因此,例如:
// Initialize some component state in either your constructor or getInitialState function
constructor(props){
super(props);
this.state = {userInput: this.props.user.first_name};
}
// Have a function that updates state when your input changes
onInputChange(event) {
this.setState({ userInput: event.target.value });
}
// Then set the value equal to your userInput state and add an onChange
// prop to the input tag in your render method.
render() {
return (
...
<input
type="text"
id="first_name"
name="first_name"
className="form-control"
value={this.state.userInput}
onChange={this.onInputChange.bind(this)} />
)
}
然後該字段的值初始化爲它正在通過this.props.user.first_name
所提供的價值,同時還保持編輯。
編輯:
正如在評論中指出,雖然有效,這實際上是在反應的反模式。由於子組件的初始狀態只被調用一次,因此從父項到子項的值的更改不會導致子項的狀態發生任何變化。如果用例明確地設置了一個你不想要的或者期望在組件生命週期中改變的初始值(儘管那時它不是一個好的模式),但是如果你確實希望初始值是可變的你有兩個選擇。
選項一:將狀態置於父組件中,它可能屬於它。然後,子組件應該接收並渲染髮送它的任何道具。初始值的更改在父組件狀態下處理,道具被視爲不可變,並且所有內容都保持同步。
方案二:如果因任何原因,你都需要從道具確定狀態,你還指望那些道具改變,你可以使用componentWillReceiveProps(nextProps)
生命週期的方法來保持同步的一切。這將允許你檢查this.props
對nextProps
並進行任何狀態變化,如果他們是必要的:
componentWillReceiveProps(nextProps) {
if(nextProps.user.first_name !== this.props.user.first_name){
this.setState({
userInput: nextProps.user.first_name
});
}
}
這裏給DOCS鏈接以備將來參考。
你想在現場展示什麼? –