英文:
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<Props> = ({children}) => {
return (<><p>{children.a}</p><div>{children.b}</div></>);
}
The call for said component would look like
<SomeComponent>{{a: "foo", b: 1}}</SomeComponent>
Alternative
type Props = {
a: string;
b: number;
};
const SomeComponent: React.FC<Props> = ({a, b}) => {
return (<><p>{a}</p><div>{b}</div></>);
}
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)
<SomeComponent {...{a: "foo", b: 1}} />
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论