反应-预先填写表格 [英] React - pre-populate form
问题描述
我需要预填充一个表单,以便用户可以编辑他们先前创建的博客.我正在寻找在React中做到这一点的最佳实践方法.我目前正在通过props将值传递给组件,然后将state属性设置为等于props属性,但是我已经读到这是一个反模式.我了解真理之源".但是,有什么更好的方法呢?我宁愿暂时不使用redux-form.下面是我的标题组件,下面是我从父母那里称呼它的方式.所有这些都有效,但是有更好的方法,以避免将state属性设置为props属性吗?
I need to prepopulate a form so that users can edit a blog they have previously created. I'm looking for the best-practices way of doing this in React. I am currently passing the value to a component through props, and then setting a state property to equal a props property, but I have read that this is an anti-pattern. I understand 'source of truth'. But what is a better way to do it? I would rather not use redux-form, for now. Below is my title component, and below that is how I call it from the parent. This all works, but is there a better way, in order to avoid setting a state property to a props property?
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} />
推荐答案
如果发布是在父级中维护的,则无需维护状态,除非有其他原因:对一个进行验证.
If publication is maintained in the parent, then there is no need to maintain state, unless there are other reasons: validations for one.
输入可能是不受控制的组件.输入的onBlur可用于更新父项.
The input could be an uncontrolled component. The onBlur of the input can be used to update the parent.
<input
onBlur={e => this.props.onTitleChange(e.target.value)}
id="doc_title"
type="text"
defaultValue={this.props.publication.document_title} />
父组件应更新发布状态.
The parent component should update the publication state.
<DocumentTitle
publication={this.state.publication}
onTitleChange={this.handleTitleChange} />
这篇关于反应-预先填写表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!