typescript 如何将函数从React中的函数组件传递给子组件?

fgw7neuy  于 7个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(96)

我有一个模板组件,它接受子组件并呈现它,我希望在该组件中有一个函数,可用于传递给它的子组件
目前我有这个:

const Template = ({ 
  children,
}) => {
  const myFunction = () => {
    alert("test");
  }

  return (
    <>
      <div>
        {children}
      </div>
    </>
  );
};

export const MyStory: Story = {
  render: args => (
    <Template>
      my children
    </Template>
  )
}

字符串
我希望能够在MyStory呈现模板的地方使用“MyFunction”,类似这样:

export const MyStory: Story = {
  render: args => (
    <Template>
      {({ myFunction }) => {
        return (
          <>
            My children

            <button onClick={myFunction}>click me</button>
          </>
        )
      }}
    </Template>
  )
}


有什么方法可以做到这一点吗?我见过当孩子直接传递给模板时这样做,但这里不是这样,需要一些 Package 器jsx。我也见过使用Formik时这样做,它允许孩子使用Formik函数。
如果有人能帮助我,我将不胜感激!

wwodge7n

wwodge7n1#

试试这个.

const Template = ({ children }) => {
  const myFunction = () => {
    alert('test');
  };

  return (
    <div>
      {React.Children.map(children, child =>
        React.cloneElement(child, { myFunction })
      )}
    </div>
  );
};

const ChildComponent = ({ myFunction }) => {
  return (
    <>
      My children
      <button onClick={myFunction}>click me</button>
    </>
  );
};

export const MyStory = {
  render: args => (
    <Template>
      <ChildComponent />
    </Template>
  ),
};

字符串

相关问题