reactjs - 我怎么能告诉 typescript Prop 来自 react 克隆元素?

标签 reactjs typescript

我有一个收集组件包裹了我所有的 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/

相关文章:

javascript - 在 React 中单击按钮时,如何在输入字段的任意位置直接插入文本?

javascript - 映射对象的特定特定数组

javascript - 元组类型的问题

javascript - 函数名, "onButtonClick"或 "onClickButton"

javascript - 如何将对象列表数组合并为单个数组

javascript - 智能组件和dumb组件之间的 React-Redux 数据流

javascript - React-Grid-Layout:如何在调整大小时重新渲染项目

java - 如何在部署在heroku上的react应用程序中配置Web服务url以访问也部署在heroku中的java REST Web服务

javascript - 我需要帮助来合并对象数组中的值 - Javascript

typescript - JSX 元素类型 'RouterLink' 没有任何构造或调用签名