Javascript 如何在特定节点上装载嵌套的react组件?
我有一个简单的嵌套组件。我将Javascript 如何在特定节点上装载嵌套的react组件?,javascript,reactjs,Javascript,Reactjs,我有一个简单的嵌套组件。我将HelloWorld嵌套在按钮中。但是我想在一个特定的div上挂载HelloWorld(即“hello”id)。可能吗 index.html <body> <div id="hello"></div> <div id="btn"></div> </body> jsx var HelloWorld=React.createClass({ render:function(){
HelloWorld
嵌套在按钮中
。但是我想在一个特定的div上挂载HelloWorld(即“hello”id)。可能吗
index.html
<body>
<div id="hello"></div>
<div id="btn"></div>
</body>
jsx
var HelloWorld=React.createClass({
render:function(){
返回(
你好,世界!
)
}
});
var期权={
txt:“我快到了!”,
柜台:10
}
var按钮=React.createClass({
handleClick:function(){
警报(“您单击了”);
},
render:function(){
返回
{this.props.options.txt}
{this.props.options.counter}
//我能把这个挂在hello上吗?
}
});
render(,document.getElementById(“btn”);
是的,您可以,但不能像在代码中那样直接:您不能在根react容器之外装载react组件
选项1(这或多或少是标准做法)创建1个react容器并将所有内容装入其中: index.html:
<body>
<div id="myApp"></div>
</body>
App.js:
var MyApp = React.createClass({
render: function(){
return (
<div>
<HelloWorld />
<Button options={this.props.options} />
</div>
)
}
});
// other code unchanged..
ReactDOM.render(<MyApp options={options}/>, document.getElementById("myApp"));
var MyApp=React.createClass({
render:function(){
返回(
)
}
});
//其他代码保持不变。。
ReactDOM.render(,document.getElementById(“myApp”);
选项2(不推荐)
或者,您可以创建两个完全独立的react容器。请注意,这些react容器不能用react框架语言相互通信
(index.html未更改)
app.js
// (other code unchanged) ...
ReactDOM.render(<HelloWorld />, document.getElementById("hello"));
ReactDOM.render(<Button options={options}/>, document.getElementById("btn"));
//(其他代码未更改)。。。
render(,document.getElementById(“hello”);
render(,document.getElementById(“btn”);
PS:我在示例代码中遗漏了var选项,以关注您的问题
// (other code unchanged) ...
ReactDOM.render(<HelloWorld />, document.getElementById("hello"));
ReactDOM.render(<Button options={options}/>, document.getElementById("btn"));