javascript - 在 React 中,在嵌套节点和不同分支中的兄弟节点之间传递数据的首选设计模式是什么?
问题描述
我有一个场景,我对如何处理有点困惑。如果我要从最低级别一直到父级进行通信,我觉得有很多重构工作要做。我对使用 React 非常陌生(现在几天),我不知道是否有更简单的解决方案来在组件之间传递数据。我读过一些资料,说孩子对父母对其他孩子最好,但我没有看到曾曾孙对父母对孩子的提及。我已经看到有关 Context API、ComponentDidMount/Update 的提及,但我不确定最好的方法是什么。
我在这个网页上创建了一个数据浏览器,所以我们有 RootComponent、LeftPanel 和 Graph 组件。
LeftPanel 包含一个 Explorer 组件,它将遍历多个级别的数据。在最后一级数据上,如果单击,它应该显示一个 Graph 组件(通过条件渲染)。
前任:
父母
export default class RootComponent extends React.Component {
render() {
return (
<div className="flex-row flex-grow">
<LeftPanel />
//Need to conditionally render this
<Graph />
</div>
)
}
}
LeftPanel 是父级中的一个容器,它将容纳一个资源管理器
export default class LeftPanel extends React.Component {
... (bunch of other logic)
render() {
return (
<Card className="flex-column default-vertical-spacing">
<div className="content">
<Explorer
..........>
</div>
</Card>
)
}
}
Explorer 保存数据以及“药丸”或单击按钮,该按钮将显示更多级别的数据
export default class Explorer extends React.Component<IExplorerProps> {
... (bunch of logic)
render() {
if(!this.props.items || this.props.items.length == 0){
return <span>Loading</span>
}
return (
<ExpandablePill
............../>
)
}
}
ExpandablePill 是可以持续下降的数据
export default class ExpandablePill extends React.Component<ExpandablePillProps, ExpandablePillState> {
render() {
...
//Here I want to do: If this ExpandablePill was clicked AND it has no children, display a graph.
}
}
这是在父 RootComponent 下,但我需要知道是否单击了没有级别的 ExpandablePill 以显示图表(或让父 RootComponent 知道我现在可以显示图表)
export default class Graph extends React.Component {
render() {
return (
<LineChart
...
</LineChart>
);
}
}
任何建议,将不胜感激!如果这是重复的,我很抱歉。
解决方案
推荐阅读
- android - Android Stuido:如何更改用于使用 Gradle 构建的 Kotlin 版本
- android - 使用 Android 数据绑定在 EditText text.length() > 0 时启用按钮
- javascript - 样式化的组件主题提供者没有将对象传递给 gatsby 中的道具
- oracle-apex - 具有行跨度的 Oracle APex 经典报告行模板
- kubernetes - Kubernetes(在 Docker for Windows 中)Postgres 的卷配置
- typescript - 如何使用任意字符串键声明类型化对象 - 缺少索引签名?
- java - 如何避免函数有多个参数
- json - Flutter用数组解析JSON
- pandas - 通过将行转换为列来重塑(分组或旋转)熊猫数据框
- reactjs - 使用来自 api 调用的 reducer 异步更新状态