当我们使用时ReactDOM.render(<Component/>,document.getElementById("container"));,组件被渲染到提到的元素.如果这里的div已经有一些现有内容怎么办?可以React将渲染的组件附加到它吗?例如:
HTML:
<div id = "container">Hello, React!</div>
Run Code Online (Sandbox Code Playgroud)
JSX:
var Component = React.createClass({
render: function(){
return(
<p>Hello to you too!</p>
)
}
})
ReactDOM.render(<Component/>, document.getElementById("container"));
Run Code Online (Sandbox Code Playgroud)
据我所知,这是做你所要求的唯一方法(因为我试图做同样的事情):
let divs = document.getElementsByClassName("some_class")
for (let i = 0; i < divs.length; i++) {
const id = Math.random() //or some such identifier
const d = document.createElement("div")
d.id = id
divs[i].appendChild(d)
ReactDOM.render(<SomeComponent/>, document.getElementById(id))
}
Run Code Online (Sandbox Code Playgroud)
如果有人知道一种更清洁/更好的方法来将react组件附加到现有的<div>而不先附加新的 empty <div>,请加入!
当您在 div 中渲染 React 组件时,其内容将被您创建的组件的内容替换。
<script src="https://facebook.github.io/react/js/jsfiddle-integration.js"></script>
<div class = 'outer-container'>
<p>
I can see this hello.
</p>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
<p>
Hello React
</p>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
JSX
var Hello = React.createClass({
render: function() {
return (
<div className="Button">
<span className="left" onClick={function() {alert("left")}}>Left</span>
<span className="right" onClick={function() {alert("right")}}>Right</span>
<span className="middle" onClick={function() {alert("middle")}}>Middle</span>
</div>
);
}
});
ReactDOM.render(<Hello name="World" />, document.getElementById('container'));
Run Code Online (Sandbox Code Playgroud)
你可以在这里看到一个小提琴:JSFIDDLE
| 归档时间: |
|
| 查看次数: |
9495 次 |
| 最近记录: |