Call a React component method from outside

前端 未结 11 1531
灰色年华
灰色年华 2020-11-28 04:56

I want to call a method exposed by a React component from the instance of a React Element.

For example, in this jsfiddle. I want to call the alertMessage

11条回答
  •  眼角桃花
    2020-11-28 05:24

    With React hook - useRef

    
    
    const MyComponent = ({myRef}) => {
      const handleClick = () => alert('hello world')
      myRef.current.handleClick = handleClick
      return ()
    }
    
    MyComponent.defaultProps = {
      myRef: {current: {}}
    }
    
    const MyParentComponent = () => {
      const myRef = React.useRef({})
      return (
        <>
          
          
        
      )
    }
    

    Good Luck...

提交回复
热议问题