簡體   English   中英

React 富文本編輯器 - 在 ENTER 上清除 state

[英]React Rich Text Editor - Clear state on ENTER

我想在按下回車鍵時清除 React 富文本編輯器 ( https://github.com/sstur/react-rte ) 的 state。

我的 state 看起來像這樣:

state = {
    value: RichTextEditor.createEmptyValue()
}

RichTextEditor組件提供了 handleReturn 屬性。 因此,我實現了以下handleReturn function:

handleReturn = () => {this.setState(prevState => ({
      ...prevState,
      value: RichTextEditor.createValueFromString("", "html")
    }));
}

當我從 RichTextEditor 本身外部的按鈕觸發 handleReturn function 時,它工作得很好,並且 state (和文本輸入區域)被正確清除。 但是,當從 enter 鍵觸發相同的 handleReturn 時,它不會清除 state; 但我可以看到 handleReturn function 被正確觸發。 我將 function 傳遞給組件,如下所示:

<RichTextEditor handleReturn={this.handleReturn} value={this.state.value}
          onChange={this.onChange}/>

任何幫助表示贊賞。 謝謝!

更新:我最終直接實現了底層的draft.js庫( https://draftjs.org/ )。 這是一個非常順利的過程,它通過繞過使用react-rte解決了這個問題。 因此,如果您有可能,建議您切換。

按下“Enter”鍵時,您可以使用 event.preventDefault() 方法。

這是它如何工作的一個小例子!

 class App extends React.Component { constructor(props) { super(props); this.state = { text: '' } this.handleChange = this.handleChange.bind(this); this.keypress = this.keypress.bind(this); } handleChange(event) { this.setState({text: event.target.value}); } keypress(e){ if(e.key === 'Enter'){ e.preventDefault(); this.setState({ send_message: this.state.text, text: '', }); } } render() { return ( <div> <textarea value={this.state.text} placeholder="Text" rows="1" className="form-textarea typing-area" onChange={this.handleChange} onKeyPress={this.keypress} /> <pre>{JSON.stringify(this.state, null, 2)}</pre> </div> ); } } ReactDOM.render(<App />, document.getElementById('app'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div>

這可以幫助,只是重置輸入有點長,但它有效

 handleReturn = () => { let {editorState} = this.state; let contentState = editorState.getCurrentContent(); const firstBlock = contentState.getFirstBlock(); const lastBlock = contentState.getLastBlock(); const allSelected = new SelectionState({ anchorKey: firstBlock.getKey(), anchorOffset: 0, focusKey: lastBlock.getKey(), focusOffset: lastBlock.getLength(), hasFocus: true }); contentState = Modifier.removeRange(contentState, allSelected, 'backward'); editorState = EditorState.push(editorState, contentState, 'remove-range'); editorState = EditorState.forceSelection(contentState, contentState.getSelectionAfter()); this.setState({editorState});

暫無
暫無

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

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