【发布时间】:2020-09-19 17:16:32
【问题描述】:
我想在我的组件树中将一个简单的字符串、数字或布尔值向上传递多个级别。根据我阅读的内容,我需要使用回调函数来执行此操作,但我似乎无法正确理解逻辑。
这是我将道具从父应用程序传递给孙子面包屑的示例。我希望这个道具实际上来自树中的最后一个孩子,即“ResultsPage”组件。
我意识到有更好的方法来做这样的事情(redux、上下文、不同的结构等),对我来说,这里的重点是学习和理解如何使用回调函数以及如何传递一个多于1 级。
新手友好请-感谢您的任何意见:)
class App extends React.Component {
render() {
return (
<>
<h1>Top level app</h1>
{/* I import the header and pass down prop */}
<Header currentLocation="Results Page" />
{/* I import the main app content */}
<ResultsPage />
</>
);
}
}
function Header(props) {
return (
<>
<h2>
This is the header element. It will have some nav items and the
breadcrumb I import
</h2>
{/* I import the breadcrumb accept the props from parent and pass the props down to child */}
<Crumbs currentLocation={props.currentLocation} />
</>
);
}
function Crumbs(props) {
return (
<>
{/* I display the props I passed down through the tree */}
<h3>
<small>This is the breadcrumb, you are on</small>{" "}
{props.currentLocation}
</h3>
</>
);
}
function ResultsPage() {
return (
<>
<p>
This is the actual results content. I would like this component to tell
the header component that I have loaded so it can update the breadcrumb
to let it know which page is currently loaded in the app.
</p>
</>
);
}
export default App;
为了完成这个问题,我放弃了以下解决方案:
Codesandbox: Solution to the initial question
Codesandbox: Additional solution for the same problem using only functional components
希望它可以帮助下一个人:)
【问题讨论】:
-
您尝试了哪些方法,为什么没有成功?
-
我花了整整 2 天时间阅读教程和文档。我的问题是它们总是非常复杂,或者它们使用类组件并且我无法将其转换为函数组件,或者当我真的只想发送一个道具时它们使用状态等等。当我试图理解上面的内容时也是如此:如何将道具向下传递几层。我找不到任何简单的例子。所以我花了几天的时间来整理教程和文档,直到我能够构建你在上面看到的这个非常简单的组件树。以上帮助我理解了!
标签: javascript reactjs react-props