将props传递给 React Router 4 中的组件

IT技术 javascript reactjs react-router
2021-05-08 14:44:33

我是 react-router 的新手,刚开始使用 react-router V4 编写应用程序。我想将props传递给由渲染的组件<Match />,我想知道这样做的“最佳”或“正确”方式是什么。

是通过做这样的事情吗?

<Match pattern="/" render={
    (defaultProps) => <MyComponent myProp = {myProp} {...defaultProps} />
}/>

这是(将 props 传递给要由 渲染的组件<Match />)甚至是使用 react-router 这样做的好习惯还是反模式或其他什么?如果是这样,为什么?

4个回答

您必须使用renderprop 而不是component传递自定义props,否则只会传递默认的 Route props( {match, location, history})。

我像这样将props传递给路由器和子组件。

class App extends Component {

  render() {
    const {another} = this.props
    return <Routes myVariable={2} myBool another={another}/>
  }
}

const Routes = (props) =>
  <Switch>
    <Route path="/public" render={ (routeProps) => 
      <Public routeProps={routeProps} {...props}/>
    }/>
    <Route path="/login" component={Login}/>
    <PrivateRoute path="/" render={ (routeProps) =>
       ...
    }/>
  </Switch>
render() {
  return (
    <Router history={browserHistory}>
      <Switch>
        <Route path="/" 
           render={ ()  => <Header 
             title={"I am Title"} 
             status={"Here is my status"}
           /> }
        />
        <Route path="/audience" component={Audience}/>
        <Route path="/speaker" component={Speaker}/>
      </Switch>
    </Router>
  )
}

我对 react-router 还很陌生,遇到了类似的问题。我已经根据文档创建了一个包装器,这似乎有效。

// Wrap Component Routes
function RouteWrapper(props) {
  const {component: Component, ...opts } = props

  return (
   <Route {...opts} render={props => (
     <Component {...props} {...opts}/>
   )}/>
 )
}

 <RouteWrapper path='/' exact loggedIn anotherValue='blah' component={MyComponent} />

到现在为止还挺好

render与定义的方法结合使用,如下所示:

class App extends React.Component {
  childRoute (ChildComponent, match) {
    return <ChildComponent {...this.props} {...match} />
  }

  render () {
    <Match pattern='/' render={this.childRoute.bind(this, MyComponent)} />
  }
}