React - 预填充表单

IT技术 forms reactjs
2021-05-20 23:54:52

我需要预填充一个表单,以便用户可以编辑他们之前创建的博客。我正在寻找在 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} />
1个回答

如果在父级中维护发布,则无需维护状态,除非有其他原因:验证之一。

输入可能是不受控制的组件。输入的 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} />