Draft-js编辑器导致反向输入

Draft-js editors causing reversed input

本文关键字:输入 编辑器 Draft-js      更新时间:2023-09-26

我有一个需要多个文本输入的应用程序,为了格式化和自定义,我选择了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回调之前更新状态。

我无法真正看到您提供的代码,但听起来您的问题是您在每次更改上重新创建EditorState(使用EditorState.createEmpty()EditorState.createWithContetnt())。这不起作用,因为它只恢复内容-而不是光标位置,选择等。

我解决这个问题的方法是,我只创建一次 EditorState ,即如果它不存在。然后,在每次更改时,我通常更新EditorState ,同时将contentState保存到(在我们的示例中)数据库中。这里重要的是,您不能使用contentState来创建新的EditorState

所以下次EditorState不存在时,使用EditorState.createWithContent(contentStateFromDB)初始化它