React - pre-populate form

坚强是说给别人听的谎言 提交于 2021-01-21 07:48:13

问题


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>
    )    
  }
}

call from parent:

 <DocumentTitle publication={this.props.publication} />

回答1:


If publication is maintained in the parent, then there is no need to maintain state, unless there are other reasons: validations for one.

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} />


来源:https://stackoverflow.com/questions/39515960/react-pre-populate-form

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!