问题描述
我在反应功能组件中有一个 RTE,由于某种原因,当输入文本时光标停止向前移动,导致文本向后输入。
现在,我已经知道问题出在哪里,但我没有解决方案。我确实发现 this 问题与他们在更新状态时通过添加 setContentFromString(nextProps.value)
解决的问题相同,但我收到以下错误
TypeError: react_rte__WEBPACK_IMPORTED_MODULE_5___default.a.setContentFromString is not a function
这是我的组件。
export default props => {
const { value,onChange,error,row,readOnly,className,...rest } = props;
const [internalValue,setInternalValue] = React.useState(
value ? RichTextEditor.createValueFromString(unescape(value),'html') : RichTextEditor.createEmptyValue()
);
React.useEffect(() => {
setInternalValue(
value ? RichTextEditor.createValueFromString(unescape(value),'html') : RichTextEditor.createEmptyValue()
);
},[value]);
const classes = useStyles({ row });
// the problem area
function change(value) {
setInternalValue(value);
if (onChange) {
const trimmed = value.toString('markdown').trim();
if (trimmed.length === 0 || (trimmed.length === 1 && trimmed.charCodeAt(0) === 8203)) {
onChange(null);
} else onChange(escape(value.toString('html')));
}
}
return (
<RichTextEditor
customStyleMap={customStyles}
toolbarConfig={toolbarConfig}
value={internalValue}
onChange={change}
readOnly={readOnly}
toolbarClassName={classes.toolbar}
editorClassName={clsx(readOnly ? null : classes.editor,error ? classes.error : null)}
className={clsx(classes.root,className)}
{...rest}
/>
);
};
解决方法
internalValue
被意外设置为随每次击键而变化的值,因此触发 useEffect
并最终将光标设置为位置 1。
通过使用 React.useRef
,我能够比较更改并使其正常工作。