我有一个需要多个文本输入的应用程序,为了格式化和自定义,我选择了 draft-js
作为我的编辑器,但是我遇到了一个非常令人困惑的输入问题。
当我在编辑器中输入时,我最近按下的键被打印在编辑器的开头,反转我的整个输入,就好像插入符号总是在该行的第一个索引处一样。
我有 3 个编辑器,每个编辑器都有一个 onChange,它使用编辑器当前的 contentState
更新 redux 存储。重新呈现页面时,每个编辑器都会呈现,并将各自的 contentState
转换为 EditorState
。
这是我的代码:
main.js
render() {
/* Each Editor has a similar block as below */
let coverEditorState = EditorState.createEmpty()
let coverContentState = _.get(data, 'details.message.cover.contentState')
if (typeof coverContentHTML != "undefined"){
coverEditorState = EditorState.createWithContent(coverContentState)
}
return (
...
<Composer
editorState={coverEditorState}
onChange={this._handleCoveringLetterChange.bind(this)}
/>
...
)
}
Composer.js
class Composer extends Component {
constructor() {
super()
this.state = { editorState: EditorState.createEmpty(), styleMap: {} }
}
componentWillReceiveProps( nextProps ) {
this.setState({ editorState: nextProps.editorState })
}
onChange( editorState ) {
let nextState = Object.assign({}, this.state, { editorState })
let currentContentState = editorState.getCurrentContent()
let changeObject = {
contentState: currentContentState
}
this.setState(nextState)
this.props.onChange(changeObject)
}
render() {
return (
<Editor
editorState={this.state.editorState}
onChange={this.onChange.bind(this)}
/>
)
}
}
我试过返回 SelectionState
和 ContentState
,将两者结合起来,然后重新渲染,但这只会导致更多的问题和错误。
最佳答案
我刚刚遇到(并解决)了一个类似的问题。
如果你遇到和我一样的问题,那是因为调用 setState
实际上是在排队更新状态,而它在调用 this.props 之前没有被应用.onChange
。可以理解的是,这似乎使 draft.js
失控。
尝试改变:
this.setState(nextState)
this.props.onChange(changeObject)
到:
this.setState(nextState, () => {
this.props.onChange(changeObject);
});
这将确保在调用父 onChange
回调之前更新状态。
关于javascript - Draft-js 编辑器导致反向输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39873382/