我需要预填充一个表单,以便用户可以编辑他们之前创建的博客。我正在寻找在 React 中执行此操作的最佳实践方法。我目前正在通过 props 将值传递给组件,然后将 state 属性设置为等于 props 属性,但我已经读到这是一种反模式。我理解“真相的来源”。但是什么是更好的方法呢?我现在宁愿不使用 redux-form。下面是我的标题组件,下面是我从父级调用它的方式。这一切都有效,但有没有更好的方法,以避免将 state 属性设置为 props 属性?
import React, { Component, PropTypes} from 'react';
export default class DocumentTitle extends Component{
constructor(props) {
super(props);
this.state = {inputVal:this.props.publication.document_title}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event) {
this.setState({inputVal: event.target.value});
}
componentWillReceiveProps(nextProps){
this.setState({inputVal: nextProps.publication.document_title})
}
render (){
return (
<div >
<label>Title</label>
<div>
<input onChange={this.handleChange} id="doc_title" type="text" value={this.state.inputVal}/>
</div>
</div>
)
}
}
来自家长的电话:
<DocumentTitle publication={this.props.publication} />