首页 > 解决方案 > ReactJs 函数式组件将函数添加到 eventListener 然后调用它

问题描述

是否可以在功能组件中创建事件侦听器,然后从 chrome 控制台调用它?

例如:

const Component = () => {
   const [hook,setHook] = useState();

   const handlerFunction = (arg) => {
      console.log(arg);
   }

   // how to add an event listener?
   return <div>Hello world<div>
}

标签: javascriptreactjsreact-functional-component

解决方案


最简单的解决方案是添加一个全局变量:

const Component = () => {
    const [ value, setValue ] = useState();

    window.MY_GLOBAL_CONTAINER = (arg) => {
        setValue(arg);
        console.log(arg);
    };

   return <div>Hello world, { value }</div>
}

您可以通过以下方式访问:

MY_GLOBAL_CONTAINER('test')

使用ref可能更好:

const Component = () => {
    const [ value, setValue ] = useState();
    const ref = useRef(null);

    useEffect(()=>{
        ref.current.handlerFunction = (arg) => {
            setValue(arg);
            console.log(arg);
        };
    },[])

    return <div ref={ ref } id="containerElementInsideTheDom">Hello world, { value }</div>
}

您可以通过以下方式访问:

document.getElementById('containerElementInsideTheDom').handlerFunction('test')

推荐阅读