2016-11-25 100 views
0

我試圖在用戶輸入後更改狀態更改時更改輸入字段的React類型方法。這是我目前的設置,但我正在尋找一種方式來做到這一點沒有在componentWillReceiveProps方法信令的DOM:當用戶輸入後狀態更改時更改輸入字段

export default class Example extends React.Component { 

constructor(props){ 
    super(props); 
    this.state = {title: props.arr.question}; 
}; 

componentWillReceiveProps(nextProps){ 
    if(nextProps.arr.question !== this.state.title){ 
    let id = "question" + this.props.arr.key; 
    document.getElementById(id).value = nextProps.arr.question; 
    this.setState({title: nextProps.arr.question}); 
    } 
} 
    render(){ 

    return(<div> 
<input type="text" id={"question" + this.props.arr.key} defaultValue={this.state.title} placeholder="Enter your title."/> 
      </div> 
     ) 
    } 
} 

我假設是,當狀態發生變化,我將看到輸入變化以及。實際上,出於某種原因,除了輸入字段外,其他情況都會發生。所以唯一認爲我發現的作品是在componentWillReceiveProps方法中引用DOM並像那樣改變它。

有沒有更好的方法來做到這一點,我不知道?

回答

1

您可以通過在您的輸入中直接設置值state中的值來創建受控組件。退房my answer here,應用程序類似。

在你的代碼

所以修改爲:

export default class Example extends React.Component { 

constructor(props){ 
    super(props); 
    this.state = {title: props.arr.question}; 
    this.handleTitleChange = this.handleTitleChange.bind(this); 
    // ^--necessary to be able to call setState 
}; 

handleTitleChange(e){ 
    this.setState({title: event.target.value}); 
    // this updates the state as the user types into the input 
    // which also causes a re-render of this component 
    // with the newly update state 
} 
render(){ 

    return(
    <div> 
     <input type="text" 
     id={"question" + this.props.arr.key} 
     defaultValue={this.state.title} 
     placeholder="Enter your title." 
     onChange={this.handleTitleChange} // to handle the change 

     value={this.state.title}/> // here is where you set 
            // the value to current state 
    </div> 
) 
} 
+0

所以基本上創建只是輸入一個單獨的組件? –

+0

不,你不需要。我已經添加了您可以對您的代碼進行修改以使其正常工作。 – Pineda

+0

唯一的區別是,在我對這個特定問題的輸入中,我不是直接在這個特定輸入中輸入標題,而是另一個輸入。但你的解決方案工作。我所要做的就是去掉'defaultValue'道具,添加一個'onChange'道具並讓onChange通過設置狀態來處理標題變化,而不是通過vanilla JS直接調用DOM。 –