【发布时间】:2020-08-22 17:28:16
【问题描述】:
我目前在 App.js 中定义了我的应用程序中的所有路由。希望能够将状态(作为道具)从 Alignment 组件向下传递到 GPfSOA 组件。
function App() {
return (
<Router>
<div className="App">
<Nav />
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" exact component={About} />
<Route path="/alignments" exact component={Alignments} />
<Route path="/alignments/:id" exact component={Alignment} />
<Route path="/alignments/segmentinfo/:id" exact component={Segments} />
<Route path="/alignments/segmentinfo/:id/:segid" exact component={Segment} />
<Route path="/alignments/getpoint/:id" exact component={GPfSOA} />
<Route path="/alignments/getstatoff/:id" exact component={GSOfPA} />
<Route path="/alignments/getalsfromxy/:x/:y" exact component={AlignList} />
<Route path="/alignments/getsegsfromxy/:x/:y" exact component={SegmentList} />
<Route path="/alignments/post/create" exact component={AddAlignment} />
<Route path="/alignments/put/update/:id" exact component={EditAlignment} />
<Route path="/alignments/ptso/list" exact component={TogglePoints} />
<Route path="/alignments/ptso/list/:ptid" exact component={Point} />
<Route path="/" render={() => <div>404</div>} />
</Switch>
</div>
</Router>
);
}
从父级到最大孙级的顺序是 App > Alignments > Alignment > GPfSOA。尝试将 item.alignment(对齐的名称)从 Alignment 组件向下(或向上)传递到 GPfSOA 组件,以便它可以在那里呈现。 item.alignment 是 Alignmnet 组件状态的一个属性。
我是否需要将它们设置为嵌套路由才能完成此操作(也就是从 App.js 中剪切并粘贴所有属于 Alignment 组件的子级的路由,然后将它们粘贴到 Alignment 组件中)?
很难理解如何将特定组件定义为父组件,而将另一个组件定义为该组件的子组件。我看到的所有示例都假设您想将 App.js 中的 props 传递给其他组件。寻找使用 React Hooks 和 React Router 的示例(函数而不是类),在这些示例中,您将 props 从“低于”App.js 的组件传递到层次结构中更靠下的另一个组件。希望这是有道理的。
找到了很多例子,例如 this one '在 Route 组件中将函数作为渲染道具传递'(据说是推荐的方法)
const PropsPage = () => {
return (
<h3>Props Page</h3>
);
};
const App = () => {
return (
<section className="App">
<Router>
...
<Link to="/404-not-found">404</Link>
<Link to="/props-through-render">Props through render</Link>
<Switch>
...
<Route exact path="/props-through-render" render={(props) => <PropsPage {...props} title={`Props through render`} />} />
<Route component={NoMatchPage} />
</Switch>
</Router>
<a href="/about">about with browser reload</a>
</section>
);
};
export default App;
但就像我之前所说的,这个示例以及我发现的所有其他示例都假设您希望将道具从 App.js 传递到另一个组件。
【问题讨论】:
标签: reactjs react-router parent-child react-router-dom react-props