【问题标题】:react-router: passing props to a component that is rendered with <Link />react-router:将 props 传递给使用 <Link /> 渲染的组件
【发布时间】:2016-03-19 13:48:19
【问题描述】:

我正在使用 react-router 的&lt;Link /&gt;,这样当用户点击链接时,myComponent 就会被渲染。

我的问题是,我怎样才能将道具从Navigation 组件传递到myComponent?这不起作用,但我正在尝试将 element.name 道具从 Navigation 传递给 myComponent

class Navigation extends Component {
  const items = store.getState().items.map((element, index) =>
    <Link to={element.id} name={element.name}> element.id </Link>
  )

  render() {
    return (
      {items}
    )
  }
}

这是路由设置和组件设置:

<Route path=":id" component={myComponent} />

// I'd like to pass in props to be used here from the Navigation component, for example, a name prop passed through <Link />

class myCompnent extends Component {
  render() {
    return (
      <div>
        <p> hello {this.props.name} </p>
      </div>
    )
  }
}

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    您可以做的是通过将props 附加到父组件中的组件链接来传递它们,并在子组件中使用componentWillReceiveProps 方法获取它们。

    例如:

    父组件

    <Link to {`element.id/{$element.name}`}>{element.id}</Link>
    

    子组件

    componentWillReceiveProps(nextProps) {
        if (nextProps.value !== this.props.value) {
            console.log(this.props); //Here you can fetch the props which you have passed
        }
    }
    

    【讨论】:

      【解决方案2】:

      react-router Link

      我认为没有办法将道具从 传递给组件,但是使用 Link 的“查询”参数可以通过路径传递一些东西,它将作为查询添加到路径上,例如:?姓名=杰克&aa=bb

      <Link to={element.id} query={{ name: element.name }}>{element.id}</Link>
      

      并从组件中的 this.props.location.query 中获取

      componentDidMount: function () {
          var query = this.props.location.query;
          if ( query && query.name ) {
              this.setState({
                  name: name
              });
          } 
      }
      
      // in render
      <p> hello {this.state.name} </p>
      

      【讨论】:

      • 我明白了,但是像这样将整个对象作为道具传递下去是不合适的,对吧? say {name: "bob", age: 55, location: "California"} 如果全局存储中的整个对象都不能传入组件,组件如何访问应用状态?
      • 我使用的一种方法是在包装应用程序组件中获取这些信息,并使用道具传递它们。链接标签实际上是一个 标签,它不是为将这些状态传递给组件而设计的。
      • 我想我的问题是我不明白组件在通过 呈现时如何访问特定的数据 假设我点击了指向用户个人资料的链接,好吧我必须将用户个人资料的数据作为道具传递。我怎么做?我必须只传入配置文件名称(作为参数附加)吗?并使用 store.getState().users 来匹配用户的参数和数据对象?这似乎是一种访问用户个人资料数据的冗长乏味的方式。
      • 我认为 myCompnent 最好从存储中获取用户数据,并使用参数 :id 来获取确切的数据。
      猜你喜欢
      • 2019-12-05
      • 2017-09-14
      • 2017-03-18
      • 2017-02-13
      • 2015-07-12
      • 2021-12-15
      • 2018-05-05
      • 2019-03-10
      • 2016-10-28
      相关资源
      最近更新 更多