react中父組件使用子組件方法
forwardRef , useImperativeHandle 作用
- forwardRef: 將ref父類的ref作為參數傳入函數式組件中,本身props只帶有children這個參數,這樣可以讓子類轉發父類的ref,當父類把ref掛在到子組件上時,子組件外部通過forwrardRef包裹,可以直接將父組件創建的ref掛在到子組件的某個dom元素上
- useImperativeHandle : 在函數式組件中,用於定義暴露給父組件的ref方法。
當父子組件都為函數時,調用子組件方法
-
父組件
-
const EditableTable = () =>{ const ref = useRef() const childrenData = ()=>{ console.log(ref.current.innerFn); } return ( <div> <button onClick={childrenData}>qurem</button> <Detils ref={ref} /> </div> ) } export default EditableTable
-
-
子組件
-
import React, { useState ,forwardRef ,useImperativeHandle,} from 'react'; import {Form} from 'antd'; // @Form.create(); const Detils = forwardRef(({...props},ref) =>{ const [data,setData] = useState([]) const innerFn = () => { console.log('子組件'); } useImperativeHandle(ref, () => ({ innerFn, }), [innerFn]); return ( <div> my name is lilie </div> ) }) export default Detils
-
當父組件為class,子組件為函數組件時。父組件發生變化
-
父組件
-
import React, { Component} from 'react'; // import TabsTable from '../commpents/TabsTable' import Detils from './detils'; class EditableTable extends Component { constructor(props) { super(props) this.state = { } this.ref = React.createRef({}) } setDate = (value) =>{ console.log(value); } childrenData = () =>{ console.log(this.ref.current); } render() { return ( <div> <button onClick={this.childrenData}>qurem</button> <Detils setData={this.setDate} ref={this.ref} /> </div> ) } }
-
當父子組件都為class時
-
父組件
-
import React, { Component} from 'react'; // import TabsTable from '../commpents/TabsTable' import Detils from './detils'; class EditableTable extends Component { constructor(props) { super(props) this.state = { } this.ref = React.createRef({}) } setDate = (value) =>{ console.log(value); } childrenData = () =>{ console.log(this.Child.getFun); } bindRef = () =>{ } render() { return ( <div> <button onClick={this.childrenData}>qurem</button> <Detils setData={this.setDate} onRef={c=>this.Child=c} /> </div> ) } }
-
-
子組件
-
class Detils extends Component { constructor(props){ super(props) this.state = { } if(props.onRef){//如果父組件傳來該方法 則調用方法將子組件this指針傳過去 props.onRef(this) } } getFun = () =>{ console.log('子組件'); } render() { return ( <div> my name is lilie </div> ) } } export default Detils
-