简体   繁体   English

在ES6中编写时,使用React中的props将复杂对象传递给子组件的正确方法是什么?

[英]What is the correct way to pass a complex object to a child component using props in React when writing in ES6?

Now that we have ES6 and can use spread I've seen some people write code like this: 现在我们有了ES6并可以使用传播,我已经看到有些人编写了这样的代码:

class Parent extends Component {
  ...
  render() {
    return (
      <UserProfile {...this.props.user} onClick={this.doSomething} />
    )
  }
}

This would set each property of user model as a prop on the UserProfile component. 这会将用户模型的每个属性设置为对UserProfile组件的支持。 The alternative would be something like this: 另一种可能是这样的:

<UserProfile user={this.props.user} onClick={this.doSomething} />

Is one of these approaches considered the better practice? 这些方法之一被认为是更好的做法吗? I know which version I'm leaning towards, but I want to know if the community has already landed on doing it one way or the other. 我知道我要使用哪个版本,但是我想知道社区是否已经以一种或另一种方式进行开发。

Few quick inputs - 快速输入-

  • Obviously, spread is better for props which are not closely related, apart from the fact that all of them are owned by the same component. 显然,对于不紧密相关的道具,散布效果更好,除了它们都属于同一组件。 A complex object is better suited for grouping tightly coupled/grouped properties together, the best example being style. 复杂对象更适合将紧密耦合/分组的属性分组在一起,最好的示例是样式。
  • Spread gives most clarity, at a glance, I can look at the propTypes to determine the usage. 一目了然,Spread可以提供最清晰的信息,我可以查看propTypes来确定用法。 However if you have a lot of props, you should look at the possibility of grouping some of them together. 但是,如果您有很多道具,则应考虑将其中一些道具组合在一起的可能性。
  • The purpose of the component has a role too. 组件的目的也起作用。 A UserProfile component is very specific and it implies several props related to the profile would be required. UserProfile组件非常具体,这意味着需要与该配置文件相关的多个道具。 In this case, I'd prefer complex object when the data model is easily available/constructible in the parent component. 在这种情况下,当数据模型在父组件中易于使用/可构造时,我更喜欢复杂的对象。 However, if you want to support say appearance or behavior related props, like displayLoginHistory etc, which don't tie in with the data model, it'd be better to use spread to keep coherent props. 但是,如果您想支持与外观或行为相关的道具,例如displayLoginHistory等,但它们不与数据模型绑定,则最好使用点差来保持道具的一致性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM