reactjs - Typescript,函数参数中使用解构 props 的 React 会导致 {children} 出现问题
所以我发现一件事,在 TypeScript 中,如果你使用像 AirBNB 这样的风格指南,它更倾向于在函数的大括号中解构 props:
interface MyComponentProps {
children: React.ReactNode
}
export default function MyComponent({children}: MyComponentProps) {
return (
<div>{children}</div>
);
}
我有一个规则要求在声明中使用 spread 操作符,当完成后,{children} 不被认为是有效的 React 元素。我会得到以下错误:
对象不能作为 React 子元素
这显而易见。你把 children 作为参数传入,然后把它们放在你想要的位置(当时,我正在提取一些代码,并制作一个元素来包装 {children},以实现特殊的格式)。
我发现重构代码效果更好,特别是像直接引用的元素,或者先赋值给一个变量。我在以下方法上更顺利:
<div>{props.children}</div>
和
const children = props.children;
<div>{children}</div>
但是尤其是,函数参数解构弄坏了我的代码。发生了什么?