javascript - 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>
}
解决方案
最简单的解决方案是添加一个全局变量:
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')
推荐阅读
- python - Python lxml soupparser 失败并出现“无效的 PI 名称”
- android - Leanback ListRow 在屏幕中心滚动
- java - 如何从图像列表中制作视频?
- reactjs - 将 React 16 应用程序升级到 Apollo 2 问题
- tfs - 如何在 TFS 中重命名多个标签
- c - 如何读取在预期浮点数末尾错误输入的字符?
- python - Python,Pandas:如何更改 DataFrame.plt.density() 的带宽选择?
- java - 如何对自身进行递归回溯?
- visual-studio-code - 我可以根据文件类型设置 VS Code 默认 EOL 吗?
- weather-api - 是否有过去 NOAA 天气预报的 API(预报档案)?