Passing a Ref from a Child to a Parent in React with Class Component

爷,独闯天下 提交于 2020-06-29 04:06:15

问题


I have an iFrame in a child component, and want to pass a ref of the iframe to the parent component so I can do a postMessage to the iframe. I am unsure how to implement forwarding refs from child to parent.

Thanks!


回答1:


Here's an example how can you do it

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:


If you want your child reference, that's easy...

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

Then you can call child functions in your parent like this.child.childFunction().

If you want to get your child's child reference, just continue this pattern.

Your child class: Set your grandchild in your render().

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

Your parent class: Call the child component's reference's grandchild key.

var grandchild = this.child.grandchild;


来源:https://stackoverflow.com/questions/62476826/passing-a-ref-from-a-child-to-a-parent-in-react-with-class-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!