gpt4 book ai didi

javascript - 如何将数据从子 Web 组件传递到它的直接父元素

转载 作者:行者123 更新时间:2023-12-05 00:31:45 27 4
gpt4 key购买 nike

我基本上需要将一个值传递给我的 Web 组件,然后我会对它做一些随机的事情,现在我想将这个新值传递回我的 React 组件。我怎么做?

function MyReactcomp() {
const [state, setState] = useState("Justin is cool");
return (
<div className="Wrapper">
<customweb-component state={state} />
</div>
);
}
现在在 customweb-component 中,我将状态更改为“No your not!!”。如何将此值从我的 Web 组件传递回
我的真实组件?我知道我可以向下传递一个函数,因为你只能向下传递字符串

最佳答案

你应该使用 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>
);
}
而且,如果您需要 观察 对于引用元素的更改,您可以使用普通 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>
);
}
如果您发现这样做太多次,您可以将此行为抽象为自定义 Hook 。例如:
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>
);
}

关于javascript - 如何将数据从子 Web 组件传递到它的直接父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72325785/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com