# react hook useRef parent call child function ```jsx const Child = React.forwardRef((props, ref) => { const [title, setTitle] = React.useState("123"); const refA = React.useRef(123); const alert = () => { console.log("I have a pen."); }; const getAlert = (val) => { alert("getAlert from Child"); setTitle(val); }; React.useImperativeHandle(ref, () => ({ setTitle, refA, getAlert })); return ( <div> {title} <button onClick={() => { ref.current.getAlert("pen"); }} > child 修改 </button> </div> ); }); const App = () => { const childRef = React.useRef(); return ( <div> <Child ref={childRef} /> <button onClick={() => { console.log(childRef); childRef.current.getAlert("apple"); }} > parent 修改 </button> </div> ); }; ReactDOM.render(<App />, document.querySelector("#app")); // class component 也可以 class App extends React.Component { constructor(props) { super(props); this.childRef = React.createRef(); } render() { return ( <div> <Child ref={this.childRef} /> <button onClick={() => { console.log(this.childRef); this.childRef.current.getAlert("apple"); }} > parent 修改 </button> </div> ); } } ``` ### 如果用 redux 可以設定 forwardRef: true 才可以取到 ref ```jsx const connectApp = connect(mapStateToProps, mapDispatchToProps, null, { forwardRef: true, })(SearchResult) ```