我需要预先填充一个表单,以便用户可以编辑他们之前创建的博客。我正在寻找在 React 中执行此操作的最佳实践方法。我目前正在通过 props 将值传递给组件,然后将状态属性设置为等于 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} />
如果发布在父级中维护,则无需维护状态,除非有其他原因:其中之一是验证。
输入可能是不受控制的组件。输入的 onBlur 可用于更新父级。
<input
onBlur={e => this.props.onTitleChange(e.target.value)}
id="doc_title"
type="text"
defaultValue={this.props.publication.document_title} />
父组件应该更新发布状态。
<DocumentTitle
publication={this.state.publication}
onTitleChange={this.handleTitleChange} />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)