【问题标题】:Passing a Ref from a Child to a Parent in React with Class Component使用类组件在 React 中将 Ref 从子级传递给父级
【发布时间】:2020-10-10 02:17:00
【问题描述】:

我在子组件中有一个 iFrame,并且想将 iframe 的 ref 传递给父组件,以便我可以对 iframe 执行 postMessage。我不确定如何实现从孩子到父母的转发参考。

谢谢!

【问题讨论】:

  • 尝试使用从父组件到子组件的回调。不确定这是否可行,但这似乎是将某些东西从孩子传递给父母的唯一方法。
  • 我有一个类似问题的答案,How to set one component's state from another component in React -- 这里我讨论如何设置子引用。希望这会有所帮助!

标签: javascript reactjs next.js


【解决方案1】:

这是一个例子,你怎么做

const { forwardRef, useRef, useState, useEffect } = React;

const Child = forwardRef((props, ref) => {
  const computeDataUrl = (value) => {
    return `data:text/html,${encodeURI(value)}`
  }

  const [data, setData] = useState(computeDataUrl('Init'))
    
  const onMessage = ({data, origin}) => {
    setData(computeDataUrl(data));
  }
  
  useEffect(() => {
    const iFrameElement = ref && ref.current;
    
    if(iFrameElement) {
      const iFrameWindow = iFrameElement.contentWindow;
      
      iFrameWindow.addEventListener("message", onMessage, false);
    }
  
    return () => {
      iFrameWindow.removeEventListener("message", onMessage);
    }
  }, [])
  
  return <iframe ref={ref} src={data} width="400" height="300" sandbox="allow-same-origin allow-scripts">
  </iframe>
})

const Parent = () => {
  const ref = useRef();
  
  useEffect(() => {
    
    const iFrameElement = ref && ref.current;
    
    if(iFrameElement) {
      const postMessage = iFrameElement.contentWindow.postMessage;
      postMessage("Message from parent"); 
    }
  
  }, [ref])

  return <Child ref={ref}></Child>
}

ReactDOM.render(
    <Parent />,
    document.getElementById('root')
  );
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

<div id="root"></div>

【讨论】:

    【解决方案2】:

    如果您希望您的孩子参考,这很容易...

    <ChildComponent
        ref={(instance) => {this.child = instance}}
    />
    

    然后你可以在你的父母中调用子函数,比如this.child.childFunction()。

    如果您想获得孩子的孩子参考资料,只需继续此模式即可。

    您的子类: 将您的孙子设置为您的render()。

    render() {
        return (
            <GrandChildComponent
                ref={(instance) => {this.grandchild = instance}}
            />
        );
    }
    

    你的父类:调用子组件引用的grandchild键。

    var grandchild = this.child.grandchild;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 2018-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多