[英]React passing props down through switch element
我在通過React元素(例如Switch和Route)傳遞道具時遇到問題。 在下面的示例中,我想將儀表板組件的所有道具傳遞到Account組件。 有沒有辦法做到這一點?
App.js
<Dashboard>
<Switch>
// Dashboard props to Account component
<Route path="/account" render={props => <Account {...props} /> } exact />
<Route path="/someothercomponent" component={Someothercomponent} />
</Switch>
</Dashboard>
Dashboard.js
render() {
const children = React.Children.map(this.props.children, child => {
var router = React.cloneElement(child, { image: this.state.image });
return router;
// Like this the router Element does receive the image prop from
// the Dashboard component. Now this image prop needs to be
// passed on to the Account component.
}
是的,改為使用render
屬性。
<Route path="path" render={() => <MyComponent {...this.props} />} />
問題在於組件正在覆蓋渲染道具。
刪除component={Account}
我還在(props)
周圍添加了括號以提高可讀性
<Dashboard>
<Switch>
<Route
path="/account"
render={(props) => <Account {...props} /> }
exact
/>
<Route
path="/someothercomponent"
component={SomeOtherComponent}
/>
</Switch>
</Dashboard>
或者:
const renderMergedProps = (component, ...rest) => {
const finalProps = Object.assign({}, ...rest);
return( React.createElement(component, finalProps)
);
}
const PropsRoute = ({ component, ...rest }) => {
return (
<Route {...rest} render={routeProps => {
return renderMergedProps(component, routeProps, rest);
}}/>
);
}
<Router>
<Switch>
<PropsRoute path='/login' component={Login} auth={auth} authenticatedRedirect="/" />
<PropsRoute path='/trades' component={Trades} user={user} />
</Switch>
</Router>
我喜歡一些已經存在的答案。 為了給您一種不同的方式解決此問題的感覺,還有一些需要學習並添加到工具箱中的東西。 我會說使用上下文。 上下文提供了一種通過組件樹傳遞數據的方法,而不必在每個級別手動傳遞道具。 https://reactjs.org/docs/context.html
因此,如果您進入自己的帳戶並不得不再次傳遞道具,那么這可能是實現此目標的好地方。
正確設置后,您可以在頁面上執行類似的操作。 但是同樣,您不僅要傳遞一個道具,還要傳遞所有道具。 然后,如果您還需要將它們傳遞給下一個組件<<<,這就是上下文的重點。 我認為使用上下文比使用組件要好,因為考慮到有狀態組件通常受到限制,因此您的狀態會更好。 有了上下文,您的Account組件可以有幾個孩子,而不必完全傳遞道具就可以完成想要實現的目標。
<AppContext.Consumer>
{({prop1, prop2, prop3}) => {
}}
</AppContext.Consumer>
假設您在使用React.createContext()時為變量AppContext命名。 這個想法是,在某些級別傳遞道具可能有些煩人,但是使用上下文,您可以隨時引入屬性,而不必擔心是否正確傳遞了道具。 在某些情況下,請確保完整閱讀本文,而在某些情況下,請不要使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.