【发布时间】:2019-05-15 08:10:23
【问题描述】:
我写了一个自定义的内容可编辑组件,如下所示
export default class TextEditor extends React.Component {
constructor(props) {
super(props);
this.ref = React.createRef();
}
onChange = (e) => {
let value = e.target.innerHTML;
this.props.onChange(value);
}
render() {
const { enabled , onChange , style, className, value } = this.props;
return (
<div>
<div contentEditable={enabled}
dangerouslySetInnerHTML={{ __html: value }}
ref={this.ref}
onInput={this.onChange}
style={{
...style,
height: '80px',
overflow: 'auto',
cursor: enabled ? 'text' : 'inherit',
}}
className={`form-control form-control-sm ${className}`}
placeholder="Optional Notes..."
/>
</div>
)
}
}
每当我在可编辑内容上键入内容时,光标都会移动到可编辑区域的开头。 这是因为 this.props.onChange(value);更新外部的值并发生重新渲染。如何防止重新渲染时光标重置??
【问题讨论】: