【问题标题】:How to call a function from Props interface in Typescript/React如何从 Typescript/React 中的 Props 接口调用函数
【发布时间】:2021-11-10 11:12:31
【问题描述】:

我正在尝试从子组件更新父组件的状态。我在 Props 接口中传递了一个函数,但我似乎无法使用我的 clickHandler 调用它。

父组件中有用户信息,应该从组成注册的各种小组件更新。

这似乎是正确的方法吗?

App.tsx

  const updateName = (
        e: React.MouseEvent,     // Function to update parent state
        firstName: string,       // Triggered by child components
        lastName: string
    ) => {
        setFirstName(firstName);
        setLastName(lastName);
    };

使用此函数作为道具渲染组件:

  <FullName
      firstName={""}
      lastName={""}
      updateName={(e, first: string, last: string) =>
          updateName(e, first, last)
      }
  />;

在 ChildComponent.tsx 中

这是道具界面:

interface NameProps {
    firstName: string;
    lastName: string;
    updateName: (e: React.MouseEvent, first: string, last: string) => void;
}

这是我要调用函数的地方,以便将状态数据从子级发送到父级,作为 updateName 中的参数!

    function handleClick(e: React.FormEvent<HTMLButtonElement>) {
        console.log(first, last);

        // I want to call NameProps.updateName here

    }

如果这完全是错误的方法,请告诉我,但我似乎非常接近。

【问题讨论】:

    标签: reactjs typescript components


    【解决方案1】:

    那么是什么阻止您从孩子调用 updateName() 呢?您可以粘贴您的子组件的代码吗?是类还是函数组件?

    我是这样做的:

    在父母中:

    const Parent = () => {
      const myFunction = function (someArgument) {
        // do stuff
      }
    
      return (
      <div>
        <Child stringParameter="foo" myFunction={myFunction}/>
      </div>
      );
    };
    

    在孩子中:

    const Child = ( { stringParameter, myFunction} ) => {
      myFunction(stringParameter);
    
      return (
        <div>lorem ipsum</div>
      );
    };
    

    我已经让它尽可能简单,所以我希望这能回答你的问题(没有界面等)。当然道具解构也是为了可读性。

    【讨论】:

    • 您好,感谢您的回答。我最终解决了这个问题。这是一个指定我作为论点包括哪些道具的问题。已更新问题:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多