gpt4 book ai didi

javascript - 使用 draft-js 自动大写句子的第一个字母

转载 作者:行者123 更新时间:2023-11-30 20:56:04 25 4
gpt4 key购买 nike

我正在使用 Reactjs 和 draftjs 库创建富文本编辑器。我想自动大写句子的第一个字母。

import React from 'react';
import ReactDOM from 'react-dom';
import {Editor, EditorState} from 'draft-js';

class MyEditor extends React.Component {
constructor(props) {
super(props);
this.state = {editorState: EditorState.createEmpty()};
this.onChange = (editorState) => this.setState({editorState});
}
render() {
return (
<Editor editorState={this.state.editorState} onChange={this.onChange}
autoCapitalize="sentences"/>
);
}
}

ReactDOM.render(
<MyEditor />,
document.getElementById('container')
);

我创建的组件不会在句点后自动大写。为什么自动大写不起作用?有没有更好的方法让它发挥作用?

最佳答案

我只是发现自己在 Draft.js 中遇到了同样的情况:需要实现自动大写,但发现内置的 Draft prop 没有任何作用,所以我自己制定了方法来实现这一点。

  1. 这是我创建的一个实用函数,用于查询 Draft.js 中光标前的字符:

    const getCharsPrecedingFocus = (
    contentState: any,
    selectionState: any,
    numberOfChars: number,
    ): string => {
    const currentBlock =
    contentState.getBlockForKey(selectionState.getAnchorKey());
    const currentBlockText = currentBlock.getText();
    const endOfText = selectionState.getEndOffset();

    return currentBlockText.slice(
    endOfText - numberOfChars,
    endOfText,
    );
    };
  2. 现在我们可以检查新句子开头是否有一个字符应该大写。将此代码放入作为 Prop 传递的 handleBeforeInput 方法中:

    const handleBeforeInput = (chars: string, editorState: any) => {
    const NON_CAPITALISED_REGEX = /^(?:\.\s)([a-z])$/;

    if (NON_CAPITALISED_REGEX.test(precedingThreeChars)) {
    const autoCapitaliseMatch =
    precedingThreeChars.match(NON_CAPITALISED_REGEX);
    if (autoCapitaliseMatch && autoCapitaliseMatch[1]) {
    const capitalisedChar = autoCapitaliseMatch[1].toUpperCase();

    const contentStateWithCapitalisedChar = Modifier.replaceText(
    contentState,
    selectionState.merge({
    anchorOffset: focusOffset - 1,
    focusOffset: focusOffset,
    }),
    capitalisedChar + chars,
    );

    EditorState.push(
    editorState,
    contentStateWithCapitalisedChar,
    'insert-characters'
    );
    return 'handled';
    }
    }
    }

一些其他注意事项:

我使用 test RegEx 方法来检查匹配自动大写模式的字符串,而不是 match,因为这是一个每次都会调用的操作用户按下一个键,test 应该比 match 更快。尽管它可能不会对用户体验产生影响,除非您处理的是非常长的文档。

*编辑:在我在这里发布的原始代码中,我忘记定义precedingThreeChars。只需像这样添加 const precedingThreeChars =
getCharsPrecedingFocus(contentState, selectionState, 3);

关于javascript - 使用 draft-js 自动大写句子的第一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47649511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com