簡體   English   中英

我該如何使用props的初始內容進行ReactJS textarea加載,但同時接受傳入的props和用戶的更新?

[英]How can I make a ReactJS textarea load with initial content from props, but accept updates both from incoming props AND the user?

我有一個帶有<textarea>的React組件。 我希望此<textarea>具有以下所有特征:

  • 可編輯的,例如必須使用defaultValue OR( value WITH onChange
  • 傳入內容決定了初始內容
  • 傳入道具更改時內容也會自動更改

如果我使用defaultValue ,則由於父級的修改道具,組件更新時<textarea>不會更新。

如果我按React文檔此SO回答 中所述valueonChange模型一起使用,則會陷入陷阱,並且無法使用來自父級的傳入prop來修改<textarea>的狀態,因為:

  • <textarea>value必須指向其組件的狀態
  • 組件狀態只能由getInitialState的傳入道具設置; setState不能在componentDidUpdate使用; 所以我永遠都無法更新狀態,因此,我的<textarea>value將在重新渲染時更新

所以我的問題是,我如何在ReactJS中有一個<textarea> ,其value可以由用戶,初始加載時的傳入道具以及傳入道具的更新來更新?

到目前為止,我想到的唯一討厭的解決方法是使用“非托管”狀態,將我自己的JSON道具添加到組件上以代替正式的React狀態。 但這不是“反應方式”。

如果有幫助,請遵循簡化的代碼。

該代碼可在初始組件加載時工作,但不再使用道具,因此無法從道具更新<textarea>內容。

var Input = React.createClass({
  componentDidUpdate: function() {
    // when component updates, can't use setState here to update state,
    // and thus can't update <textarea> content
  },
  getInitialState: function() {
    return {
      draftPath: this.props.draftPath,
      draftBody: this.props.draftBody
    };
  },
  handlePathChange: function(event) {
    this.setState({
      draftPath: event.target.value
    });
  },
  handleBodyChange: function(event) {
    this.setState({
      draftBody: event.target.value
    });
  },
  render: function() {
    return (
      <div id='cyoag-input-container'>
        <textarea id='cyoag-input-path' type='text'
          value={this.state.draftPath} onChange={this.handlePathChange} >
        </textarea>
        <textarea id='cyoag-input-body' type='text'
          value={this.state.draftPath} onChange={this.handleBodyChange} >
        </textarea>
      </div>
    );
  }
}

您可以使用componentWillReceiveProps(nextProps)來更新包含傳入屬性的組件狀態。

不要忘了將組件prop與nextProps進行比較,以便僅在必要時調用setState

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM