gpt4 book ai didi

javascript - 通过路由中的高阶组件传递 Prop

转载 作者:可可西里 更新时间:2023-11-01 02:40:05 24 4
gpt4 key购买 nike

我的高阶组件有问题。我正在尝试从 <Layout /> 传递 Prop 组件沿着一条路线(React Router v4)。路由中指定的组件由 HOC 包装,但我传递的 Prop 永远不会到达组件。

此外,如果不使用 export default () => MyHOC(MyComponent),我就无法使用 HOC .我不明白为什么,但这可能与它有关?

Layout.js

const Layout = ({ location, initialData, routeData, authenticateUser }) => (
<Wrapper>
<Container>
<Switch>
// how do I get these props passed through the HOC? render instead of component made no difference.
<Route exact path="/pages/page-one" component={() => <PageOne routeData={routeData} title="PageOne" />} />
<Route exact path="/pages/page-two" component={() => <PageTwo routeData={routeData} title="PageTwo" />} />
<Route component={NotFound} />
</Switch>
</Container>
</Wrapper>
)

export default Layout

Page.js

// I've tried swapping to (WrappedComponent) => (props) without success
const Page = (props) => (WrappedComponent) => {
const renderHeader = props.header
? <Header title={props.headerTitle} />
: false
return (
<Wrapper>
{renderHeader}
<Container withHeader={props.header}>
<WrappedComponent />
</Container>
</Wrapper>
)
}

export default Page

PageOne.js

class PageOne extends React.Component {
render() {
return (
<Content>
<Title>{this.props.title}</Title> // <----- not working!
{JSON.stringify(this.props.routeData, null, 4)} // <---- not working!
</Content>
)
}
}

export default () => Page({ header: true, headerTitle: 'header title' })(PageOne)

// does not work without () => Page
// when using just export default Page I get the "Invariant Violation: Element type is invalid:
// expected a string (for built-in components) or a class/function (for composite components)
// but got: object. Check the render method of Route." error.

最佳答案

您还需要一个箭头来使您的 Page 成为 HOC。它接受参数、包装的组件并且必须返回一个组件。你的是在获取 WrappedComponent

之后渲染的
const Page = (props) => (WrappedComponent) => (moreProps) => {
const renderHeader = props.header
? <Header title={props.headerTitle} />
: false
return (
<Wrapper>
{renderHeader}
<Container withHeader={props.header}>
<WrappedComponent {...moreProps} />
</Container>
</Wrapper>
)
}

现在你可以这样使用了

export default Page({ header: true, headerTitle: 'header title' })(PageOne)

关于javascript - 通过路由中的高阶组件传递 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44694176/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com