在React中,是否有覆盖children props使用复杂对象的良好理由?

huangapple go评论64阅读模式
英文:

Is there ever a good reason to override the usage of children props in React with a complex object?

问题

React似乎允许您通过children属性传递对象,我想知道是否有任何好的理由要这样做,而不是使用props来传递对象。

示例:

type Props = {
  children: {
    a: string;
    b: number;
  }
};

const SomeComponent: React.FC<Props> = ({children}) => {
  return (<><p>{children.a}</p><div>{children.b}</div></>);
}

调用此组件的方式如下:

<SomeComponent>{{a: "foo", b: 1}}</SomeComponent>

另一种方式:

type Props = {
  a: string;
  b: number;
};

const SomeComponent: React.FC<Props> = ({a, b}) => {
  return (<><p>{a}</p><div>{b}</div></>);
}

调用此组件的方式如下(忽略此案例中属性可以显式传递,不需要对象解构,因为用例是传递一个对象):

<SomeComponent {...{a: "foo", b: 1}} />
英文:

React seems to allow you to pass objects via the children prop and I was wondering if there's ever a good reason that you'd want to do so when the alternative of just passing the object as props exists?

ex.

type Props = {
  children: {
    a: string;
    b: number;
  }
};

const SomeComponent: React.FC&lt;Props&gt; = ({children}) =&gt; {
  return (&lt;&gt;&lt;p&gt;{children.a}&lt;/p&gt;&lt;div&gt;{children.b}&lt;/div&gt;&lt;/&gt;);
}

The call for said component would look like

&lt;SomeComponent&gt;{{a: &quot;foo&quot;, b: 1}}&lt;/SomeComponent&gt;

Alternative

type Props = {
  a: string;
  b: number;
};

const SomeComponent: React.FC&lt;Props&gt; = ({a, b}) =&gt; {
  return (&lt;&gt;&lt;p&gt;{a}&lt;/p&gt;&lt;div&gt;{b}&lt;/div&gt;&lt;/&gt;);
}

The call for said component would look like (ignore the fact that the props can be explicit in this case and there's no need for object destructuring since the use case is for passing an object)

&lt;SomeComponent {...{a: &quot;foo&quot;, b: 1}} /&gt;

答案1

得分: 1

没有,没有充分的理由来在React中用一个复杂对象覆盖children属性。就像在其他库/框架中一样,React也有受限的关键词、模式和原则。

这可能不会引发编译错误,但你将来会让其他开发人员对你的代码感到困惑,降低代码的可读性。

英文:

> Is there ever a good reason to override the usage of children props in React with a complex object?

tl;dr - no.

No, there is no a good reason to override children property in React. Just like in other libraries/frameworks there are restricted keywords, patterns and principles, so they are in React.

It may not throw any compile errors, however you will simply confuse other developers using your code in the future and you will decrease the readability of your code.

huangapple
  • 本文由 发表于 2023年2月7日 03:00:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75365506.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定