2016-10-05 186 views
14

我是react-router的新手,刚开始使用react-router V4编写应用程序。我想将道具传递给由<Match />提供的组件,我想知道什么是“最佳”或“正确”的方式。将道具传递给React Router 4中的组件

这是通过做这样的事情吗?

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

这是(通过道具由<Match />被渲染组件),即使一个很好的做法来与路由器这样做还是一个反什么的;如果是这样,为什么?

+0

看起来对我好。 –

回答

0

我会这样做,以提高清晰度。

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


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

通过这个你的router代码不会弄乱!

+0

这是有效的吗? [文档](https://react-router.now.sh/Match)说''呈现'采取了一个函数,而在你的例子中,你正在传递一个组件实例 –

+0

我的坏!更新了答案! –

+0

嗯,抱歉再次问,但这仍然有效?根据文档,当您提供组件实例时,“component”采用组件实例*构造函数 –

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

您每次重新绑定组件调用渲染器的时间。 – Qwerty

0

render道具是为写行内的比赛,所以你的例子是通过额外的道具的理想方式。

+0

在这种情况下,最好使用'component'而不是'render'吗? – Qwerty

+0

@Qwerty我刚编辑我的答案,删除该评论。如果你正在使用内联函数,你还应该使用'render'。用'component'做这件事确实是效率低下的(你将在每次渲染中卸载/安装一个新组件)。 –

5
render() { 
    return(
     <Router history={browserHistory}> 
     <div> 
      <Route path="/" render={() => <Header 
      title={"I am Title"} 
      status={"Here is my status"} 
      /> 
      }/> 
       <Route path="/audience" component={Audience}/> 
       <Route path="/speaker" component={Speaker}/> 
     </div> 
     </Router> 
    ); 
} 
+0

可能与你的q无关?但在反应路由器4的工作方式来做到这一点。 – Jsun

+1

它看起来像你的评论应该是你的答案的一部分。 – flaviodesousa

+0

是的,在反应路由器v4许多变化,你不会除了会像以前一样工作。 – Jsun

2

必须使用render道具,而不是component通过自定义道具,否则只能default Route props传递({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> 
0

我是相当新的反应路由器,并遇到类似的问题。我已经创建了一个基于Documentation的包装,似乎工作。

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

到目前为止好

相关问题