在App.tsx中,我把<Left /> 和<Right /> 传递给一个名为 "儿童 "的导入组件。<SplitScreen />
显然,从React 18开始,"children "这个道具需要明确地被输入。如果我把它输入为React.Element[] ,那么SplitScreen.tsx 工作,但App.tsx 抛出:
Type 'Element' is not assignable to type 'ElementType<any>'
如果我把它输入为React.ReactNode (这似乎是目前的共识),App.tsx 工作,但SplitScreen.tsx 抛出:
Type 'ReactNode' must have a '[Symbol.iterator]()' method that returns an iterator
不,React.ReactNode[] 也没有帮助,它只是将错误改为:
Type 'ReactNode[] | undefined' must have a '[Symbol.iterator]()'
// package.json
{
//...
"dependencies": {
"@babel/preset-typescript": "^7.18.6",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@babel/plugin-transform-typescript": "^7.18.12",
"@types/react": "^18.0.17",
"@types/react-dom": "^18.0.6",
"@vitejs/plugin-react": "^2.0.1",
"typescript": "^4.6.4"
}
}
// App.tsx
const LeftHandComponent = () => {
return <h1 style={{ backgroundColor: 'blueviolet' }}>Left</h1>;
};
function App() {
return (
<SplitScreen {...appProps}>
<LeftHandComponent></LeftHandComponent>
<!-- Type 'Element' is not assignable to type 'ElementType<any>' -->
<RightHandComponent></RightHandComponent>
</SplitScreen>
);
}
// SplitScreen.tsx
interface SplitScreenProps {
// extends PropsWithChildren {
leftWeight: number;
rightWeight: number;
children?: React.ReactNode;
// children: React.ElementType[];
}
export const SplitScreen = ({ leftWeight, rightWeight, children }: SplitScreenProps) => {
// Type 'ReactNode' must have a '[Symbol.iterator]()' method that returns an iterator
const [Left, Right] = children; // HERE
return (
<Container>
<Pane weight={leftWeight}>
<Left></Left>
</Pane>
<Pane weight={rightWeight}>
<Right></Right>
</Pane>
</Container>
);
};