在 React 打字稿上将功能从一个组件传递到另一个组件的正确方法

Proper way of passing function from one component to other on React typescript

我是 typescript 的新手,我在将父组件的功能作为 prop 传递给另一个组件时遇到问题,我在网上搜索但没有任何用处

作为参考,我在这里附上JSX代码,[TSX是我想要的]

这是父组件

export default function Notification() {
    const [notification, setnotification] = useState(['alert', 'booking'])

    return (
        <div>
            <ShowNotification setnotification={setnotification} notification={notification} />
        </div>
    )
}

这是子组件

const ShowNotification = ({notification,setnotification}) => {
    notification.map((item, index) => {
        <li>item</li>
    })
}

我的主要问题是在打字稿中指定道具类型

基本上很简单:

let my_function = () => {console.log('hi!')}

您只需将其作为参数传递即可:

return (
<>
<MyAnotherComponent my_function={my_function}></MyAnotherComponent>
</>
)

MyAnotherComponent 里面你可以这样称呼它:

props.my_function()

很少,可能对你有帮助

但总的来说,和传递其他普通道具一样。

下面是一个可以帮助您理解的基本示例:

// button.tsx
interface IProps {
  children: React.FC | string;
  onClick: (e: any) => void;
  type: "button" | "reset";
}

const Button: React.FC<IProps> = (props) => {
  return (
    <button type={props.type} onClick={props.onClick}>
      {props.children}
    </button>
  );
};

export default Button;
import Button from "./button";

export default function App() {
  const myFunction = (e: any) => {
    console.log("Event is: ", e);
  };

  return (
    <Button type="button" onClick={myFunction}>
      Click Me
    </Button>
  );
}

在这里,你可以看到,我已经将 myFunction 作为道具传递给 Button 组件,并从 Button 组件本身调用该方法,每当有人按下按钮,它从父 App.tsx 文件执行 myFunction 方法。