【问题标题】:Cannot pass the props value?无法传递 props 值?
【发布时间】:2020-06-02 05:09:38
【问题描述】:

我是新手,现在将通过props 将 id 从一个页面传递到另一个页面。但我不确定这是不是正确的传递方式。

考虑下面的代码:

<div  className="submit-button">
    <input type="submit" 
        value="Purchase" 
        className="btn btn-primary mt-2 text-capitalize " 
        onClick={this.handleClickPurchase}
    />
</div>
        handleClickPurchase(){
            window.location.href='/PurchaseInformation'
            return(
                <PurchaseInformation value={this.state.data.id}/>
            )
        }

在我的购买信息页面上

render(props){
    console.log(this.props.value)
    return (
      <div>
        <Header />
        <div>
          <h1> {this.props.value}</h1>
          <h2> Purchase Information Page is under development </h2>
        </div>
      </div>
    );
  }

【问题讨论】:

  • 从 handleClickPurchase 返回 不会做任何事情。当你去新的 url 时,你应该使用 react-router 来渲染新的组件。并且要在页面之间共享信息,您可以使用react context 或第三方库,例如 redux 和 mobx

标签: reactjs react-props prop


【解决方案1】:

正如@Ido 提到的那样,return &lt;PurchaseInformation value={this.state.data.id}/&gt; 没有做任何事情。

你是否在你的父组件中渲染PurchaseInformation? 如果是这样,只需在您的渲染函数中使用&lt;PurchaseInformation value={this.state.data.id}/&gt;

我会使用破坏性语法,更容易使用道具/对象。

render(){
   const {value} = this.props;
    console.log(value)
    return (
      <div>
        <Header />
        <div>
          <h1>{value}</h1>
          <h2>Purchase Information Page is under development</h2>
        </div>
      </div>
    );
  }

【讨论】:

    猜你喜欢
    • 2019-03-18
    • 1970-01-01
    • 2019-08-09
    • 2019-03-10
    • 2020-10-09
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 2018-10-24
    相关资源
    最近更新 更多