我在事件句柄上动态创建了很多react组件.代码是打击:
var node = []; //this is update with properties on user action and an element is creaed
var node = Interfaces.Embroidery.node;
var components = node.map(function(props) {
return React.createElement('g', {
id: props.id,
key: props.id
},
React.createElement('path', props));
});
var App = React.createClass({
render: function() {
return React.createElement('div', null, components);
}
});
ReactDOM.render(React.createElement(App), document.getElementById('parentDrawingNode'));
现在我想从dom中删除一个元素.即它将是一个用户动作组件或我想删除一些特殊情况和其他组件保持相同.
通过使用我们正在处理实际dom的refs,因此refs在这种情况下不适用.
你错过了React的观点.您不需要手动修改元素树.您声明性地将属性/状态映射到元素,并让React执行所有修改.
var App = React.createClass({ render: function() { // Get the node from the passed-in props var node = this.props.node; // generate the child components var components = node.map(function(props) { return React.createElement('g', { id: props.id, key: props.id }, React.createElement('path', props)); }); // render them in a div return React.createElement('div', null, components); } }); // first time it will create the DOM // after that it just modifies the DOM function renderApp(node, element) { ReactDOM.render(React.createElement(App, { node: node }), element); } // Call when you want to get rid of the App completely // and cleanup memory without reloading the page function destroyApp(element) { ReactDOM.unmountComponentAtNode(element); } // Initial render var node = Interfaces.Embroidery.node; renderApp(node, document.getElementById('parentDrawingNode')); function updateNodeOnSomeUserActionThatHappensOutsideOfReact(...) { node.push(...); // or whatever modification you want // re-render renderApp(node, document.getElementById('parentDrawingNode')); }
在这里阅读更多关于这种风格的信息:https://facebook.github.io/react/blog/2015/10/01/react-render-and-top-level-api.html
请注意,如果"用户操作"发生在React组件之外(即应用程序中的其他位置),则会执行此操作.如果"用户操作"作为React组件中的事件发生,则您只需调用render
一次,而应用程序将保留节点,state
并且只调用this.setState({ node: modifiedNodes });
更改状态,这将导致React更新您的DOM.