【发布时间】:2020-02-07 18:30:58
【问题描述】:
我想在组件之间进行切换。有两个组件,比如说组件 A 和组件 B。组件 A 是组件 B 的父组件。我可以根据一些状态更改来管理从 A 到 B 的切换。同时,我想在 B 组件的一些状态变化的基础上切换回组件 A。现在,问题是:
问。我在 A 中导入 B 组件。那么,我应该在 B 中导入 A 还是 child ? 听起来可能很幼稚,但我是初学者。
同时,我不确定这是否是一个好方法?有什么好的处理方法。我已经看到了一些问题,用于切换涉及第三个组件的位置,并将其余两个组件导入其中。 请建议我处理它。
示例: 组件A
import B from './B.js';
class A extends React.Component{
constructor(props, context){
super(props, context);
this.state = {
showB: false
}
}
onClick = () =>{
this.setState({
showB: true
});
}
render(){
return(
{
this.state.showB ? <B /> :
<div>
<Button onClick={this.onClick}>VIEW B </Button>
</div>
<h1>I am component A</h1>
)
}
}
组件 B
class B extends React.Component{
constructor(props, context){
super(props, context);
this.state = {
showA: false
}
}
onClick = () =>{
this.setState({
showA: true
});
}
render(){
return(
{
this.state.showA ? <A /> :
<div>
<Button onClick={this.onClick}>VIEW A </Button>
</div>
<h1>I am component B</h1>
)
}
}
【问题讨论】:
-
“切换”到底是什么意思?你能提供一个Minimal, Reproducible Example吗?这将使您更容易理解您的问题并提供答案。
-
@Meana 你能提一下你的代码的一些 sn-p 吗?
-
可能你可以参考:reactjs.org/docs/higher-order-components.html。使用高阶组件,您可以为两个组件设置一个状态,并通过传递道具有条件地渲染它们。
-
@Luze 示例添加
标签: reactjs