使用打字稿渲染道具

Ton*_*oli 1 typescript reactjs

我正在尝试创建一个渲染道具包装组件。它正在工作,但我收到类型错误。这也是我指向代码沙箱的链接。链接到沙箱

  1. 我收到的第一个错误是 Children 是不可调用的表达式。
  2. 第二个错误是“hello”隐式具有任何类型。

寻找react/typescript大师寻求帮助

type Props = {
  children: JSX.Element;
};


const ControlledWrapper: FC<Props> = ({ children }) => {
  const state: { hello: string } = { hello: 'hello' };

  return children(state);
};



export default function App() {
  return (
    <ControlledWrapper>
    {({ hello }) => <div>{hello}</div>}
  </ControlledWrapper>
  );
}
Run Code Online (Sandbox Code Playgroud)

moc*_*cha 5

将 的类型更改children为返回 React 元素的函数:

type Props = {
  children: (ctx: { hello: string }) => ReactElement;
};
Run Code Online (Sandbox Code Playgroud)

现在,当您使用该组件时,您将获得正确的类型:

    {({ hello }) => <div>{hello}</div>} // 'hello' is a string
Run Code Online (Sandbox Code Playgroud)

在这里试试这个。