代码之家  ›  专栏  ›  技术社区  ›  asanas

在React中将道具从路线传递到组件

  •  1
  • asanas  · 技术社区  · 7 年前

    我正在为一个项目使用react with react router,我需要将道具从路由传递给子组件。

    我有以下设置:

    应用程序。js公司

    <Switch>
      <Route exact path='/' render={()=><Home num="2" someProp={100}/>} />
      <Route path='/roster' component={Roster}/>
    </Switch>
    

    家js公司

    import React from 'react'
    
    const Home = () => (
      <div>
        <h1>Welcome to the Tornadoes Website!</h1><p>{this.props.num}</p>
      </div>
    )
    
    export default Home
    

    问题是主组件总是给出错误“未定义”。我无法理解如何解决这个问题。如果我把道具从家里搬走。js,组件渲染很好。但当我尝试访问道具时,会出现错误。

    2 回复  |  直到 7 年前
        1
  •  3
  •   kingdaro    7 年前

    无状态组件不通过访问道具 this 。它们作为参数传递给函数。

    const Home = props => (
      <div>
        <h1>Welcome to the Tornadoes Website!</h1><p>{props.num}</p>
      </div>
    )
    
        2
  •  2
  •   Omar    7 年前
    <Switch>
      <Route exact path='/' render={()=><Home num="2" someProp={100}/>} />
      <Route path='/roster' component={Roster}/>
    </Switch>
    

    import React from 'react'
    
    const Home = (props) => (
      <div>
        <h1>Welcome to the Tornadoes Website!</h1><p>{props.someProp} {props.num} </p>
      </div>
    )
    
    export default Home
    

    因为你在应用程序中将道具命名为someProp。js要访问它,你需要做道具。someProp,名称必须与您传递给它的名称匹配。持有“2”的num道具也是如此。

    实例 在父组件渲染子组件中 <Child prop1={"hello"} fun={"this is a fun prop} />

    现在在儿童中

    const Child = (props) => (
    <div> 
     {props.prop1} will render hello {props.fun} will render this is a fun prop 
    </div>
    )