使用 React Hooks 在 ReactJS 中使用来自 StencilJS 的事件?
Using events from StencilJS in ReactJS using React Hooks?
有没有人设法找到一种方法来使用 React useRef() 和 useEffect() 挂钩在 ReactJS 中使用在 StencilJS 中创建的自定义事件?
为此我查看了 StencilJS 文档,他们只介绍了数组和自定义对象。
我是前端开发的新手,所以任何帮助都是朝着正确方向迈出的一步。
提前致谢。
在 this article 的指导下,我已经使用 useRef() 和 useEffect() React 挂钩为我的功能组件解决了这个问题,如下所示:
import React, { useState, useRef, useEffect } from "react";
const Form = () => {
const [ name, setName ] = useState('');
const nameInputField = useRef(null);
useEffect(() => {
const { current } = nameInputField;
//First parameter is the name of the event in Stencil component
//Second parameter is the custom function
current.addEventListener('onChanged', () => setName('Steph'););
//Component is unmounting so removing the event listener
return () => current.removeEventListener('onChanged', () => setName('Steph'););
}, []);
return (
<stencil-component-with-event
ref={nameInputField}
value={name}
type='text'
/>
)
}
我希望这是有道理的:)
有没有人设法找到一种方法来使用 React useRef() 和 useEffect() 挂钩在 ReactJS 中使用在 StencilJS 中创建的自定义事件?
为此我查看了 StencilJS 文档,他们只介绍了数组和自定义对象。
我是前端开发的新手,所以任何帮助都是朝着正确方向迈出的一步。
提前致谢。
在 this article 的指导下,我已经使用 useRef() 和 useEffect() React 挂钩为我的功能组件解决了这个问题,如下所示:
import React, { useState, useRef, useEffect } from "react";
const Form = () => {
const [ name, setName ] = useState('');
const nameInputField = useRef(null);
useEffect(() => {
const { current } = nameInputField;
//First parameter is the name of the event in Stencil component
//Second parameter is the custom function
current.addEventListener('onChanged', () => setName('Steph'););
//Component is unmounting so removing the event listener
return () => current.removeEventListener('onChanged', () => setName('Steph'););
}, []);
return (
<stencil-component-with-event
ref={nameInputField}
value={name}
type='text'
/>
)
}
我希望这是有道理的:)