我有一个收集组件包裹了我所有的 child 。 我假设这次聚会必须将“ Prop :{index}”传递给每个 child 。
收集.tsx
const Gather: React.FC = ({
children
}) => {
return {
Children.map(children, (child, index) => {
return React.cloneElement(child as ReactElement, {
page: index + 1
});
})
}
}
GatherChild.tsx
const GatherChild = ({ page }) => {
return <div>{ page }</div>
}
应用.tsx
const App = () => {
return <Gather>
<GatherChild />
<GatherChild />
<GatherChild />
</Gather>
}
我怎么能告诉 typescript 我一定会给它 Prop ?
最佳答案
这是一个老问题,但也许其他人需要答案。
我们需要稍微重新安排一下代码:
interface ProvidesHeightInjectedProps {
page: boolean;
}
interface Props {
children(props: ProvidesHeightInjectedProps): React.ReactElement<any>
}
const Gather: FunctionComponent<Props > = ({
children
}) => {
return children({ page: index + 1})
}
const App = () => {
return (
<Gather>
{({ page }) => (
<GatherChild page={page} />
<GatherChild page={page} />
<GatherChild page={page} />
)}
</Gather>
)
}
关于reactjs - 我怎么能告诉 typescript Prop 来自 react 克隆元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64425743/