我基本上需要将一个值传递给我的web组件,然后我将对其执行一些随机操作,现在我想将该新值传递回我的React组件.我该怎么做?

function MyReactcomp() {
   const [state, setState] = useState("Justin is cool");
   return (
        <div className="Wrapper">
           <customweb-component state={state} />
        </div>
    );
}

现在在customweb组件中,我将状态更改为"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>
  );
}

并且,如果需要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>
  );
}

Javascript相关问答推荐

积分计算和 colored颜色 判断错误

序列查找器功能应用默认值而不是读取响应

使用print This时, map 容器已在LeafletJS中初始化

如何从JSON数组添加Google Maps标记—或者如何为数组添加参数到标记构造器

你怎么看啦啦队的回应?

如何在 cypress 中使用静态嵌套循环

无法从NextJS组件传递函数作为参数'

ChartJs未呈现

使用Nuxt Apollo在Piniastore 中获取产品细节

Angular 形式,从DOM中删除不会删除指定索引处的内容,但会删除最后一项

SPAN不会在点击时关闭模式,尽管它们可以发送日志(log)等

令牌JWT未过期

Google脚本数组映射函数横向输出

AddEventListner,按键事件不工作

如何访问此数组中的值?

对具有相似属性的对象数组进行分组,并使用串连的值获得结果

相对于具有选定类的不同SVG组放置自定义工具提示

如何在css中裁剪成一定Angular 的圆的一部分,而不需要复杂的多边形

带有JS模块模式的Rails的Importmap错误:";Net::ERR_ABORTED 404(未找到)&Quot;

鼠标进入,每秒将图像大小减小5%