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

3

我有一个需要多个文本输入的应用程序,为了格式化和自定义,我选择了 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)}
            />
        )
    }
}

我尝试返回SelectionStateContentState,将两者合并并重新渲染,但这只会导致更多的问题和错误。

2个回答

1

我刚刚遇到了一个类似的问题,并解决了它。

如果你和我遇到了同样的问题,那是因为调用 setState 实际上会将更新状态排队,而在调用 this.props.onChange 之前没有被应用。这显然会使 draft.js 混乱不堪。

尝试更改:

this.setState(nextState)
this.props.onChange(changeObject)

至:

this.setState(nextState, () => { 
    this.props.onChange(changeObject); 
});

这将确保在调用父级 onChange 回调之前更新状态。


0

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

我解决这个问题的方法是,只有在不存在时才创建EditorState。然后,在每次更改时,我通常更新EditorState并同时将contentState保存到我们的数据库中。重要的是,您不要使用contentState来创建新的EditorState

因此,下一次EditorState不存在时,它将使用EditorState.createWithContent(contentStateFromDB)进行初始化。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接