ReactJs 功能组件将功能添加到 eventListener 然后调用它
ReactJs functional component add function to an eventListener and then invoke it
是否可以在功能组件中创建事件侦听器,然后从 chrome 控制台调用它?
例如:
const Component = () => {
const [hook,setHook] = useState();
const handlerFunction = (arg) => {
console.log(arg);
}
// how to add an event listener?
return <div>Hello world<div>
}
最简单的解决方案是添加一个全局变量:
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')
是否可以在功能组件中创建事件侦听器,然后从 chrome 控制台调用它?
例如:
const Component = () => {
const [hook,setHook] = useState();
const handlerFunction = (arg) => {
console.log(arg);
}
// how to add an event listener?
return <div>Hello world<div>
}
最简单的解决方案是添加一个全局变量:
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')