[英]React – how to render additional component inside another mounted one?
Just wonder are there any approaches to render component in another component in React. 只是想知道是否有任何方法可以在React的另一个组件中渲染组件。
I render a <Scene />
component like this: 我渲染这样的<Scene />
组件:
import Scene from './Scene';
ReactDOM.render(<Scene/>, document.getElementById('root'));
And at some point I need to render another component <Building />
(for example on onClick
) so that it should be inside <Scene />
在某个时候,我需要渲染另一个组件<Building />
(例如onClick
),以便它应该在<Scene />
内部
At the current I'm trying to do so like this: 目前,我正在尝试这样做:
import Building from './Building';
ReactDOM.render(<Building/>, document.getElementById('fields'));
And this fields
container inside this render()
method is a child (pretty deep one) of <Scene />
而且此render()
方法中的此fields
容器是<Scene />
的子级(相当深)
Yes, it renders, it's located inside #fields
in HTML, but if I go to React developer tools I see this: 是的,它呈现,它位于HTML中的#fields
内,但是如果我使用React开发人员工具,我会看到:
<Scene></Scene>
<Building></Building>
React just rendering <Building>
outside of <Scene>
and I need quite the opposite. React只是在<Scene>
<Building>
之外渲染<Building>
,而我需要完全相反。
Unfortunately, conditional rendering isn't the case. 不幸的是,条件渲染并非如此。
You should only use one ReactDOM.render()
, not multiple. 您只能使用一个ReactDOM.render()
,而不要使用多个。 It's common to create 1 component (often named <App />
) and in that component you create logic. 创建1个组件(通常称为<App />
)很普遍,然后在该组件中创建逻辑。 Basically, you create the whole app in Javascript/ReactJS, and you use that line to "load" it into your html. 基本上,您可以使用Javascript / ReactJS创建整个应用程序 ,然后使用该行将其“加载”到html中。
export class App extends React.Component{
render(){
// It now returns only one component, but this is where you would put your react router
return(
<Scene />
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
export class Scene extends React.Component{
render(){
return(
<>
<div> Your normal scene here and if you want <Building /></div>
{ orSomeVariableWhichHasToBeTrue && <Building />}
</>
);
}
}
Also, I suggest trying to follow their Basics tutorial, I think you're missing the way React's intended use. 另外,我建议尝试遵循其基础知识教程,我认为您错过了React预期用途的方式。 Reading the Doc's again might help for some insights. 再次阅读文档可能有助于获得一些见解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.