2016-09-15 100 views
4

我需要预填表格,以便用户可以编辑他们以前创建的博客。我正在寻找在React中做到这一点的最佳实践方式。我目前通过道具将值传递给组件,然后将状态属性设置为等于道具属性,但我已经读到这是一种反模式。我明白'真相的来源'。但是什么是更好的方法呢?现在我宁愿不使用redux形式。下面是我的标题组件,下面是我如何从父级调用它。这一切都有效,但有没有更好的办法,为了避免将国有财产设置为道具物业?反应 - 预填充表格

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

它看起来没问题。如果你有一个ajax调用,那么redux非常方便。 – vijayst

回答

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