当您将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链接以备将来参考。
你想在现场展示什么? –