2016-09-15 79 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} />