2015-10-19 70 views
2

我有一個textarea在我的React應用程序中充滿了值。我希望這個textarea被更新,並且表單被引用來更新數據庫中的行。反應textarea的值是隻讀的,但需要更新

<textarea id="description" className="materialize-textarea" length="120" value={description} disabled={isDisabled}></textarea> 

description變量用來自數據庫的值填充textarea。該字段未被禁用。

我試圖附加一個onChange事件,它派發一個動作(redux)來更改textarea的值,但它會觸發每個字母,並且它太慢。

如何創建一個由值填充並且可編輯的textarea?

謝謝!

+0

當按鈕被點擊時,你想讓POST到你的服務器嗎?當輸入按下時?當該領域不再焦點時? – elithrar

+0

我發佈時,表單submited –

回答

2

這是一個包含兩個textareas的組件。道具與國家之間有一種受控的關係。這是投入的關鍵。注意componentWillReceiveProps。

import React, {Component} from 'react'; 

    import Actions from '../../flux/Actions'; 

    let CurrentSnipDivSty = { 
     height: 'calc(((100% - 40px) * .4) - 3px)', 
     minHeight: '9.5em', 
     width: '100%' 
    }; 

    let CurrentSnipTextAreaSty = { 
     backgroundColor: '#213919', 
     border: '1px solid #314929', 
     color: '#afac87', 
     fontSize: '1em', 
     height: 'calc(50% - 20px)', 
     overflowY: 'auto', 
     padding: '5px', 
     width: 'calc(100% - 12px)' 
    }; 

    class SnipsDetailRender extends Component { 
     render() { 
      let snip = this.state.snip.snip; 
      let comment = this.state.snip.comment; 

      return (
       <div id='CurrentSnipDivSty' style={CurrentSnipDivSty}> 
        <textarea 
         value={snip} 
         onChange={this.handleSnipChange} 
         style={CurrentSnipTextAreaSty} /> 
        <textarea 
         value={comment} 
         onChange={this.handleCommentChange} 
         style={CurrentSnipTextAreaSty} /> 
       </div> 
      ); 
     } 
    } 

    export default class SnipsDetail extends SnipsDetailRender { 
     constructor() { 
      super(); 
      this.state = { snip: {snip: '', comment: ''} }; 
     } 
     componentWillReceiveProps = (nextProps) => { 
      if ((nextProps.data.snip != this.state.snip.snip) || (nextProps.data.comment != this.state.snip.comment)) 
      this.setState({snip: nextProps.data}); 
     } 
     handleSnipChange = (ev) => { 
      let newSnip = {snip: ev.target.value, comment: this.state.snip.comment}; 
      this.setState({snip: newSnip}); 
      Actions.saveSnipEdit(newSnip); 
     } 
     handleCommentChange = (ev) => { 
      let newSnip = {snip: this.state.snip.snip, comment: ev.target.value}; 
      this.setState({snip: newSnip}); 
      Actions.saveSnipEdit(newSnip); 
     } 
    } 
+0

我使用Redux,所以狀態是以其他方式管理。謝謝您的回答。 –

+0

感謝您的回答 –