xxxxxxxxxx
import React, { useRef } from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const childRef = useRef(null);
const runChildFunction = () => {
if (childRef.current) {
childRef.current.childFunction();
} else {
console.error("Child ref is not set.");
}
};
return (
<div>
<button onClick={runChildFunction}>Run Child Function</button>
<ChildComponent ref={childRef} />
</div>
);
};
export default ParentComponent;
xxxxxxxxxx
const { Component } = React;
class Parent extends Component {
constructor(props) {
super(props);
this.child = React.createRef();
}
onClick = () => {
this.child.current.getAlert();
};
render() {
return (
<div>
<Child ref={this.child} />
<button onClick={this.onClick}>Click</button>
</div>
);
}
}
class Child extends Component {
getAlert() {
alert('getAlert from Child');
}
render() {
return <h1>Hello</h1>;
}
}
ReactDOM.render(<Parent />, document.getElementById('root'));