我正试图创建一个文本编辑器,如Draft.js,这就需要使用contentEditable。无论如何,我使用MutationObserver来检测变化,我希望能够在状态中反映DOM的变化。
当一个组件渲染到一个字符串时,findDOMNode会返回一个包含该值的文本DOM节点。
我想将突变目标与渲染的dom进行比较,并将这些变化反映在应用程序状态中。如果我使用findDOMNode,它很可能会工作,然而它已经被废弃了。有其他的方法吗?或者,有什么方法可以使用refs来实现这个功能?
举个例子,我有一个PElement类。
class PElement extends React.Component {
constructor (props) {
super(props);
this.state = {
children = []
}
/*Parse content props, etc, for children*/
this.ref = React.createRef();
this.compare = this.compare.bind(this);
}
compare (node) {
//This will allow me to check if the target of the mutation was this component.
return this.ref.current === node;
}
render () {
return (<p ref={this.ref}>{this.state.children}</p>);
}
}
至于Text类
class Text extends React.Component {
constructor (props) {
super(props);
//No state. This will be lowest level and controlled.
this.ref = React.createRef();
this.compare = this.compare.bind(this);
}
compare (node) {
return this.ref.current === node;
}
render () {
//I don't know how to create a ref to the rendered text node.
return this.props.content;
}
}
}
我试着创建一个Text节点并使用React.cloneElement,不过没有成功。
最后,我决定通过每次突变的状态来推断Text组件的位置,即通过添加或删除组件并检查父节点的子节点的childList。这样我就可以知道哪个Component渲染了哪个节点。
虽然,转念一想,我可能只是防止输入,并根据捕捉到的输入,以它应该的方式修改状态。这比较符合React的理念。