Created
June 22, 2018 08:42
-
-
Save beardlessman/7430c23a991475e072c8cd625638819d to your computer and use it in GitHub Desktop.
REACT How to call child component method from parent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Child.js */ | |
import React from 'react' | |
class Child extends React.Component { | |
componentDidMount() { | |
this.props.onRef(this) | |
} | |
componentWillUnmount() { | |
this.props.onRef(undefined) | |
} | |
method() { | |
window.alert('do stuff') | |
} | |
render() { | |
return <h1>Hello World!</h1> | |
} | |
} | |
export default Child; | |
/* Parent.js */ | |
import React from 'react' | |
import Child from './Child' | |
class Parent extends React.Component { | |
onClick = () => { | |
this.child.method() // do stuff | |
} | |
render() { | |
return ( | |
<div> | |
<Child onRef={ref => (this.child = ref)} /> | |
<button onClick={this.onClick}>Child.method()</button> | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment