2015-12-01 48 views
4

我在事件句柄上動態創建了很多反應組件。 的代碼被賦予打擊:我們可以從DOM中移除一個元素嗎?

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刪除單個元件。即它將是一個用戶操作組件,或者我想在某些特殊情況下刪除並且其他組件保持不變。

通過使用refs我們正在處理實際的dom因此refs不適用於這種情況。

回答

5

你缺少陣營的地步。您不要手動修改元素樹。您聲明性地將屬性/狀態映射到元素,並讓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組件中的事件發生,則只會調用render一次,而應用程序會將節點保存爲state,並且只會調用this.setState({ node: modifiedNodes });來更改狀態,這會導致React更新您的DOM。

0

由於您使用數組node創建反應元素,因此您可以根據後續操作添加或刪除元素。

推,切片,CONCAT等等

node.push({id: id, key: key })添加元素

node.splice()刪除元素

相關問題