我正在逐步用React替换一些Backbone视图。
我的React视图:
<div id="reactViewContent">Rendered By React</div>
我需要在其他html元素下方呈现React视图而不替换它们。
<div id="somestuff"> <div id="anotherView">Other stuff not to delete</div> <div id="placeholderForReactView"></div> </div>
我希望我的方法可以替换占位符,而不是插入占位符,以便:
React.render(React.createElement(MyTestReactView), document.getElementById('placeholderForReactView'));
可能导致:
<div id="somestuff"> <div>Other stuff not to delete</div> <div id="reactViewContent">Rendered By React</div> </div>
代替:
<div id="somestuff"> <div>Other stuff not to delete</div> <div id="placeholderForReactView"> <div id="reactViewContent">Rendered By React</div> </div> </div>
没有重复出现在Jquery上,有没有正确的方法呢?
您不需要jQuery来解决此问题。
您只需要渲染到临时DIV中并提取内容并替换现有元素即可。我添加了,id="destination"以便可以轻松地从临时元素中检索该元素。
id="destination"
var Hello = React.createClass({ render: function() { return <div id="destination">Hello {this.props.name}</div>; } }); // temporary render target var temp = document.createElement("div"); // render React.render(<Hello name="World" />, temp); // grab the container var container = document.getElementById("container"); // and replace the child container.replaceChild(temp.querySelector("#destination"), document.getElementById("destination"));