【问题标题】:I am trying to log the props of a parent component in the child component我正在尝试在子组件中记录父组件的道具
【发布时间】:2019-11-21 17:52:17
【问题描述】:

我试图在我的子组件中使用 this.state.props 将道具传递给我的父组件。

我到处都用谷歌搜索过

   choice(){
     console.log(this.props.size);
  }

{this.props.size && <DropdownItem onClick={this.choice} className="bg-info">{this.props.size}</DropdownItem>}


this is the parent component
 <DropDown
                      title="Options"
                      special={special}
                      size={size1}

【问题讨论】:

  • 不能从子组件访问父组件的props。您的意思是访问从父级传递的道具吗?
  • 那么如何使用我在父组件中传递的属性来更改状态。假设他们点击大小 2= 即 14 我希望所选对象的状态为 14

标签: reactjs state react-props


【解决方案1】:

试试这个:

choice() {
    console.log(this.props.size);
}

{this.props.size && <DropdownItem onClick={() => this.choice()} className="bg-info">{this.props.size}</DropdownItem>}

如果你想每次点击改变大小,你必须使用state而不是props

【讨论】:

  • 尝试使用onClick中的箭头符号:onClick={() =&gt; this.choice()}
  • 不,因为this 依赖于被调用的对象。如果您使用箭头符号,this 将绑定在对象上,而如果您不使用箭头符号,则 thisnull。你可以在这里阅读更多:frontarm.com/james-k-nelson/when-to-use-arrow-functions
  • 什么意思?每个DropDown 都有多个道具?
  • 可以考虑使用尺寸数组吗?
  • 好吧,主要是因为鞋码有 23 码,我肯定会一秒钟
猜你喜欢
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
  • 2019-12-09
  • 2018-06-01
  • 2021-05-24
  • 1970-01-01
  • 1970-01-01
  • 2019-02-24
相关资源
最近更新 更多