【发布时间】:2018-02-13 20:43:54
【问题描述】:
我有一个组件
import React, { Component } from 'react'
import { EditorState, convertToRaw } from 'draft-js'
import { Editor } from 'react-draft-wysiwyg'
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'
import draftToHtml from 'draftjs-to-html'
import toolbarOptions from './JpuriTextEditorOptions'
export default class TextEditor extends Component {
state = {
editorState: this.props.editorState
}
componentWillReceiveProps = nextProps => {
console.warn('componentWillReceiveProps')
console.log('nextProps.editorState', nextProps.editorState)
console.log('this.props.editorState', this.props.editorState)
this.setState({editorState: nextProps.editorState})
}
onEditorStateChange = editorState => this.setState({editorState})
onBlur = () => this.props.onBlur({key: this.props.myKey, value: draftToHtml(convertToRaw(this.state.editorState.getCurrentContent()))})
render () {
return (
<Editor
wrapperClassName={this.props.wrapperClassName}
editorClassName={this.props.editorClassName}
toolbarClassName={`toolbarAbsoluteTop ${this.props.toolbarClassName}`}
wrapperStyle={this.props.wrapperStyle}
editorStyle={this.props.editorStyle}
toolbarStyle={this.props.toolbarStyle}
editorState={this.state.editorState}
onEditorStateChange={this.onEditorStateChange}
onChange={this.props.onChange}
toolbarOnFocus
toolbar={toolbarOptions}
onFocus={this.props.onFocus}
onBlur={this.onBlur}
onTab={this.props.onTab}
/>
)
}
}
我向它传递了一个响应式道具,this.props.editorState
然后我将它设置在内部状态中以处理那里的更改。只有onBlur 我将更改保存到mongo db。
现在有一个问题。 每当我单击编辑器时,我都会多次看到 componentWillReceiveProps 日志。每次更改都会发生这种情况,因此我无法正确使用我的编辑器组件。因为每次点击和更改时,它的光标都会重置为第一个字母。
我正在使用这个draftjs库https://github.com/jpuri/react-draft-wysiwyg
编辑
问题的更多细节。 在构造函数或 componentDidMount 中将状态设置为 this.props.editorState 正在解决初始状态的问题。 但是仍然只剩下一个问题。 在另一个组件中,我具有直接与数据库一起使用的撤消重做功能。现在,如果我输入一些文字。模糊它我的更改已保存到数据库中,由于内部文本,我可以看到文本。但是,如果我单击撤消按钮,文本将从数据库中撤消,但是由于内部状态,它仍将在编辑器中可见。所以我必须刷新才能看到我的操作被撤消。 使用 componentWillReceiveProps 解决了这个问题,但是由于某种原因,每次状态更改时都会调用 componentWillReceiveProps,即使 props 没有更改。从而带来上述问题。
【问题讨论】:
-
如果你在每个收到的新道具上设置状态,那你为什么要使用内部状态呢?
标签: javascript mongodb reactjs meteor draftjs