【问题标题】:Proper way of passing function from one component to other on React typescript在 React 打字稿上将功能从一个组件传递到另一个组件的正确方法
【发布时间】:2021-12-27 07:24:36
【问题描述】:

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

作为参考,我在这里附上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>
    })
}

对我来说主要问题是在 typescript 中指定道具类型

【问题讨论】:

  • 到目前为止你尝试了什么?

标签: reactjs react-typescript


【解决方案1】:

有几个stackoverflow answers,可能对你有帮助。

但总而言之,它就像传递其他普通道具一样。

这是一个可以帮助你理解的基本示例:

// 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 组件,并从ButtonComponent 本身调用该方法,每当有人按下按钮时,它都会执行@来自父 App.tsx 文件的 987654327@ 方法。

【讨论】:

  • 如果我想传递状态,上面代码中的修改是什么
  • 您可以简单地使用某个名称 &lt;Button name={stateValue}&gt; 传递状态并在您的子组件中使用它。
  • @SanketPatil 你能接受这个答案吗,以便将来其他人可以轻松阅读它。谢谢。
【解决方案2】:

基本上很简单:

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

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

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

MyAnotherComponent 内部你可以这样称呼它:

props.my_function()

【讨论】:

    猜你喜欢
    • 2019-11-11
    • 1970-01-01
    • 2020-12-06
    • 2022-08-17
    • 2021-02-02
    • 2021-04-16
    • 2021-01-11
    • 2020-05-27
    • 1970-01-01
    相关资源
    最近更新 更多