我升级到反应18,一切都很好。今天,似乎每个使用子组件的组件都会抛出一个错误。Property 'children' does not exist on type 'IPageProps'.
在儿童道具自动包含在FC接口之前。现在看来,我必须手动添加children: ReactNode。反应儿童的正确类型是什么?
这是反应18更新的一部分,还是在我的env中搞砸了?
package.json
"react": "^18.0.0",
"react-dom": "^18.0.0",
"next": "12.1.4",
"@types/react": "18.0.0",
"@types/react-dom": "18.0.0",tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
"alwaysStrict": true,
"sourceMap": true,
"incremental": true
},
"include": ["src"],
"exclude": ["node_modules"]
}发布于 2022-04-09 16:32:07
尽管这个答案是正确的,但我想指出的是,您绝对不必使用这个PropsWithChildren助手。(它主要用于共模,而不是手动使用。)
相反,我发现手动定义它们比较容易。
在此之前
import * as React from 'react';
type Props = {};
const Component: React.FC<Props> = ({children}) => {...}之后
import * as React from 'react';
type Props = {
children?: React.ReactNode
};
const Component: React.FC<Props> = ({children}) => {...}这就是我们所需要的。
或者您可以完全停止使用React.FC。
import * as React from 'react';
type Props = {
children?: React.ReactNode
};
function Component({children}: Props): React.ReactNode {
...
}在React中,children是一个常规的道具,并不是什么特别的东西。所以你需要定义它,就像定义所有其他道具一样。以前隐藏它的打字是错误的。
发布于 2022-05-02 13:48:02
是的,React.FC类型已经改变了。但是你可以用21点来声明你自己的类型,然后对孩子们做出反应。
我的方法是创建具有如下内容的src/types/react.d.ts:
import React, { PropsWithChildren } from 'react';
export type ReactFCC<T> = React.FC<PropsWithChildren<T>>;更新#01
可以为T参数添加默认值:
import React, { PropsWithChildren } from 'react';
export type ReactFCC<T = Record<string, unknown>> = React.FC<PropsWithChildren<T>>;或
import React, { PropsWithChildren } from 'react';
export type ReactFCC<T = unknown> = React.FC<PropsWithChildren<T>>;现在可以选择不指定ReactFCC泛型中没有警告的类型。
在此之前:
export const Component: ReactFCC<SomeType> = props => {
const { children } = props;
/* ... */
}之后:
export const Component: ReactFCC = props => {
const { children } = props;
/* ... */
}发布于 2022-05-15 17:30:26
创建自定义功能组件类型(对FC的修改)。
让我们将其命名为FCC (表示:-带有子组件的函数组件;)
// Put this in your global types.ts
import { FC, PropsWithChildren } from "react";
// Custom Type for a React functional component with props AND CHILDREN
export type FCC<P={}> = FC<PropsWithChildren<P>>每当您想要在组件的children中使用props属性时,请按如下方式使用:
// import FCC from types.ts
const MyComponent: FCC = ({children}) => {
return (
<>{children}</>
)
}或
interface MyCompoProps{
prop1: string
}
const MyComponent: FCC<MyCompoProps> = ({children, prop1}) => {
return (
<>{children}</>
)
}PS这个答案看上去可能类似@Garvae的回答,但他的
ReactFCC<P>type应该像ReactFCC<P={}>一样编写,以防止以下错误: 当您没有将道具传递给组件时,Generic type 'ReactFCC' requires 1 type argument(s)会发生此错误。儿童道具应该是一种可选的道具。因此,给这些道具一个默认的{}值(即P = {})可以解决这个问题。
https://stackoverflow.com/questions/71788254
复制相似问题