【问题标题】:Confusion in props and state in REACT jsREACT js 中的 props 和 state 混淆
【发布时间】:2020-05-25 10:07:21
【问题描述】:

这里有一个简单的问题。我现在有 2 个类,AExample 类和 BExample 类。所以现在,我在 AExample 类的渲染部分创建了一个 BExample 类的实例。我已在渲染部分的 A 类中添加了此代码。

<BExample
state= {this.state}
/>

所以在 BExample 类中,当我尝试

console.log(props);

在 props 值中,我得到了 state 的值。问题是我现在很困惑,是 BExample 还是 AExample 的状态?你们的状态值代表哪个类?如果是,为什么会这样?

【问题讨论】:

  • 这是您作为道具传递给 BExample 的 AExample 的状态。
  • 随组件传递的任何对象值都会成为正在渲染的组件的道具。而状态表示组件的局部变量。您应该在此处浏览官方文档。 reactjs.org/docs/components-and-props.html
  • 您将 AExample 类的状态作为道具传递给 BExample 类。而 props 与 state 无关,除非你使用 props 来创建你的 state。所以有一个名为 state 的道具是你感到困惑的原因。

标签: reactjs state react-props


【解决方案1】:

请看,AExamplestate 现在被设置为 state 组件的 BExample 组件。

作为属性的组件的任何prop在react中被称为附加组件的prop。

所以,

<BExample
state= {this.state}
/>

在上面的例子中{this.state}AExample 的状态但是stateBExample 的一个prop。这就是为什么当您记录props 时,它会显示AExample 的状态值。

【讨论】:

    【解决方案2】:

    在 ReactJS 中,父组件的 state 变成了子组件的 props。

    因此,在A 组件中,您将'A's State' 传递给'B' component

    对于B,现在是props。因此,在B 中,如果您将console.log(props) 将获得'A's State' 的值。

    https://reactjs.org/docs/components-and-props.html

    【讨论】:

      猜你喜欢
      • 2020-05-16
      • 2017-09-12
      • 2019-02-02
      • 2015-03-15
      • 2019-06-23
      • 2018-05-04
      • 1970-01-01
      相关资源
      最近更新 更多