您应该使用React的Ref
,而不是查询DOM,如下所示:
function MyReactcomp() {
const [state, setState] = useState("Justin is cool");
// Hold the web component reference here
const myWebComp = useRef();
useEffect(() => {
myWebComp.current?.addEventListener('tab-select', (event) => {
setState(Object.keys(adminTabs[event.detail.tabIndex]));
});
}, []);
return (
<div className="Wrapper">
<customweb-component ref={myWebComp} state={state} />
</div>
);
}
并且,如果需要observe以获取引用元素中的更改,则可以使用plain useState
保留对元素的引用:
function MyReactcomp() {
const [state, setState] = useState("Justin is cool");
// Hold the web component reference here
const [webComp, setWebComp] = useState(null);
useEffect(() => {
webComp?.addEventListener('tab-select', (event) => {
setState(Object.keys(adminTabs[event.detail.tabIndex]));
});
}, [webComp]);
return (
<div className="Wrapper">
<customweb-component ref={setWebComp} state={state} />
</div>
);
}
如果您发现这样做的次数太多,可以将此行为抽象为自定义挂钩.例如:
function useWebCompProp(ref, initialValue) {
const [state, setState] = useState(initialValue);
useEffect(() => {
ref.current?.addEventListener('onState', (event) => {
// Update the state here
setState(event.detail);
});
}, []);
const setter = (newState) => {
setState(newState);
ref.current?.state = newState;
};
return [state, setter];
}
function useWebCompEvent(eventName, callback) {
// Hold the web component reference here
const myWebComp = useRef();
useEffect(() => {
myWebComp.current?.addEventListener(eventName, callback);
}, []);
return myWebComp;
}
function MyReactcomp() {
const myWebComp = useWebCompEvent(eventName, (event) => {
setState(Object.keys(adminTabs[event.detail.tabIndex]));
});
const [state, setState] = useWebCompProp(myWebComp, "Justin is cool");
return (
<div className="Wrapper">
<customweb-component ref={myWebComp} />
</div>
);
}