通过路线中的高阶组件传递道具

时间:2017-06-22 08:31:12

标签: javascript reactjs react-router react-router-v4

我的高阶组件有问题。我试图从路由中的<Layout />组件传递道具(React Router v4)。路由中指定的组件由HOC包装,但我传递的道具永远不会到达组件。

另外,我不能在不使用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.

1 个答案:

答案 0 :(得分:8)

您还需要一个箭头才能使Page成为HOC。它需要params,包装组件并且必须返回组件。在获得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)