gpt4 book ai didi

reactjs - React.render 替换容器而不是插入

转载 作者:行者123 更新时间:2023-12-03 13:06:47 24 4
gpt4 key购买 nike

我正在逐渐用 React 替换一些 Backbone View 。

我的 react View :

<div id="reactViewContent">Rendered By React</div>

我需要在其他 html 元素下方渲染 React View 而不替换它们。

<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" 以便可以轻松地从临时元素中检索该元素。

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"));

关于reactjs - React.render 替换容器而不是插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30686796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com