React.render 替换容器而不是插入 [英] React.render replace container instead of inserting into
问题描述
我正在逐渐用 React 替换一些 Backbone 视图.
我的反应视图:
由 React 渲染
我需要在其他 html 元素下方呈现 React 视图而不替换它们.
<div id="anotherView">其他不可删除的内容</div><div id="placeholderForReactView"></div>
我希望我的方法可以替换占位符而不是插入到其中:
React.render(React.createElement(MyTestReactView), document.getElementById('placeholderForReactView'));
可能导致:
<div>其他不可删除的内容</div><div id="reactViewContent">由 React 渲染</div>
代替:
<div>其他不能删除的东西</div><div id="placeholderForReactView"><div id="reactViewContent">由 React 渲染</div>
在不重复使用 Jquery 的情况下,有没有正确的方法来做到这一点?
你不需要 jQuery 来解决这个问题.
您只需要渲染到一个临时 DIV 中并提取内容并替换现有元素.我添加了 id="destination"
以便可以轻松地从临时元素中检索元素.
var Hello = React.createClass({渲染:函数(){return <div id="destination">你好{this.props.name}</div>;}});//临时渲染目标var temp = document.createElement("div");//使成为React.render(<Hello name="World"/>, temp);//抓取容器var container = document.getElementById("container");//并替换孩子container.replaceChild(temp.querySelector("#destination"), document.getElementById("destination"));
I'm gradually replacing some Backbone views with React.
My React View:
<div id="reactViewContent">Rendered By React</div>
I need to render the React view below other html elements without replacing them.
<div id="somestuff">
<div id="anotherView">Other stuff not to delete</div>
<div id="placeholderForReactView"></div>
</div>
I'd like that my method could replace the placeholder instead of inserting into it so that :
React.render(React.createElement(MyTestReactView), document.getElementById('placeholderForReactView'));
could result in:
<div id="somestuff">
<div>Other stuff not to delete</div>
<div id="reactViewContent">Rendered By React</div>
</div>
instead of:
<div id="somestuff">
<div>Other stuff not to delete</div>
<div id="placeholderForReactView">
<div id="reactViewContent">Rendered By React</div>
</div>
</div>
Without recurring at Jquery is there a correct way to do it?
You don't need jQuery to work around this issue.
You just need to render into a temporary DIV and extract the content and replace the existing element. I've added the id="destination"
so that the element can be easily retrieved from the temporary element.
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"));
这篇关于React.render 替换容器而不是插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!