将道具传递给React Router 4中的组件

问题描述 投票:21回答:6

我是react-router的新手,我刚开始使用react-router V4编写应用程序。 我想将道具传递给<Match />呈现的组件,我想知道什么是'最佳'或'正确'的方式。

这是做这样的事吗?

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

这是(通过<Match />传递道具到组件)甚至是使用react-router这样做的好习惯,还是反模式或其他东西; 如果是这样,为什么?

javascript reactjs react-router
6个回答
11
投票

您必须使用render道具而不是component来传递自定义道具,否则只传递默认路径道具{match, location, history} )。

我将我的道具传递给路由器和子组件,如此。

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>

5
投票
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>
  )
}

1
投票

我对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} />

到现在为止还挺好


0
投票

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

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

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

0
投票

render道具用于编写内联匹配,因此您的示例是传递额外道具的理想方式。


-1
投票

我将像下面这样做以提高清晰度。

const myComponent = <MyComponent myProp={myProp} {...defaultProps} />


<Match pattern="/" component={myComponent} />

这样你的router代码就不会搞砸了!

© www.soinside.com 2019 - 2024. All rights reserved.