简体   繁体   English

你如何将 React 回调 function 传递给 typescript object?

[英]How do you pass a React callback function to a typescript object?

I have a singleton class in Daemon.ts我在 Daemon.ts 中有一个 singleton Daemon.ts

export default class Daemon {
    
    private static instance : Daemon;
    callback : (tstring : string)=>void;
    t : number;

    constructor (callback: (tstring : string)=>void){
        this.data = data
        this.callback = callback;
        this.t = 0;
        window.setInterval(this.tick.bind(this), 1000)
    }

    public static getInstance(callback: (tstring : string)=>void){
        if(!Daemon.instance){ Daemon.instance = new Daemon(callback);}
        return Daemon.instance;
    }

    tick(){
        this.t = this.t + 1
        this.callback(this.t.toString());
    }

}

Then in a separate file, Timefeedback.tsx , I have:然后在一个单独的文件Timefeedback.tsx中,我有:

const TimeFeedback = () => {

    const [time, updateSimTime] = React.useState<string>("starting string");
    
    const updateTime = (tString : string) => {
      updateSimTime(tString);
      console.log(`update time called, val: ${tString}`)
    }

    const daemon = Daemon.getInstance(updateTime.bind(this));
  
    return (
      <div>
        {time}
      </div>
    );
  };

What I expect to happen:我期望发生的事情:

  • the time state is updated on each tick() from the daemon.时间 state 在守护程序的每个 tick() 上更新。

What actually happens:实际发生了什么:

  • the callback function updateTime is successfully called, and the console log prints the correct values.回调 function updateTime被成功调用,并且控制台日志打印出正确的值。 But the setState function updateTime() What happens is I get console logs from TimeFeedback.tsx with the expected value of tString printed out.但是 setState function updateTime() 发生的事情是我从tString获取控制台日志,打印出TimeFeedback.tsx的预期值。 But the setState function setSimTime never gets called, so the text in the div remains "starting time".但是 setState function setSimTime永远不会被调用,所以 div 中的文本仍然是“开始时间”。 Why is this?为什么是这样?

I have investigated, when calling print events inside of Daemon I get:我调查过,在守护进程内部调用打印事件时,我得到:

function() {
    [native code]
}

I tried to remove the .bind(this) inside TimeFeedback.tsx , but nothing changes except the print instead says:我试图删除TimeFeedback.tsx中的.bind(this) ,但除了打印内容之外没有任何变化:

tString => {
    setSimTime(tString);
    console.log(`update time called, val: ${tString}`);
  }

I also walked through with the debugger and updateSimTime does get called but it has no effect.我还浏览了调试器,并且确实调用了updateSimTime ,但它没有任何效果。

Why is that updateSimTime has no effect?为什么updateSimTime没有效果?

No need to .bind in the component无需在组件中.bind

updateTime.bind(this) doesn't make sense in a function component because a function component doesn't have a this like a class component does. updateTime.bind(this)在 function 组件中没有意义,因为 function 组件没有像 class 组件那样的this Your updateTime function can be passed directly to the Daemon.getInstance function.您的updateTime function 可以直接传递给Daemon.getInstance function。

You also need to remove the this.data = data in the Daemon constructor because there is no data variable` (as pointed out by @Konrad in the comments).您还需要删除Daemon构造函数中的this.data = data因为没有data变量`(正如@Konrad 在评论中指出的那样)。

As a best practice, I would recommend moving the code into a useEffect hook.作为最佳实践,我建议将代码移至useEffect挂钩中。

const TimeFeedback = () => {
  const [time, updateSimTime] = useState<string>("starting string");

  useEffect(() => {
    const updateTime = (tString: string) => {
      updateSimTime(tString);
      console.log(`update time called, val: ${tString}`);
    };
  
    Daemon.getInstance(updateTime);
  }, [updateSimTime]);

  return <div>{time}</div>;
};

CodeSandbox Link代码沙盒链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不创建新函数的情况下将参数传递给React + Typescript中的回调? - How to pass arguments to callback in React + Typescript without new function creation? 你如何在 React Native 中通过 object? - How do you pass object in React Native? 如何在React中将值传递给状态更改回调? - How do you pass a value to a state change callback in React? 如何使用回调从 React 组件传递数据? - How do you pass data out of a React component using a callback? 如何使用 Lit HTML 将 React hook useState() 的回调 function 传递给 web 组件的属性 - how do you pass a React hook useState() 's callback function to a web component's attribute using Lit HTML 在React中,如何将输入值传递给回调函数? - In React, how do I pass input value to callback function? 如何在 React 中将 onClick function 传递给孙子组件? - How do you pass an onClick function to grandchild component in React? TypeScript React:如何将泛型传递给 React.ComponentProps<typeof ComponentWithGenericProps> ? - TypeScript React: How do you pass a generic to a React.ComponentProps<typeof ComponentWithGenericProps>? 如何将回调函数从 React 传递给 litelement? - How to pass callback function to litelement from React? 如何在React中将参数传递给状态回调函数 - How to pass argument to the state callback function in react
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM