1. 程式人生 > >React-父組件訪問子組件內部

React-父組件訪問子組件內部

extend 方法 create 選擇 組件 code 應用 重新 reac

父子組件通信

典型數據流:父組件向後代組件傳遞props,當props更新則接收對應值的後代組件觸發重新渲染;
如果希望父組件能夠訪問子組件內部的信息則需要典型數據流之外的其他方法。

ref

React的ref表示對組件實例的引用
普通組件:
詳情鏈接
詳情鏈接

React的忠告

》》》
不要過度使用 Refs
你可能首先會想到在你的應用程序中使用 refs 來更新組件。如果是這種情況,請花一點時間,重新思考一下 state 屬性在組件層中位置。通常你會想明白,提升 state 所在的組件層級會是更合適的做法。有關示例,請參考狀態提升.
《《《

不能用高階組件傳遞refs引用,如果向一個由高階組件創建的組件的元素添加ref應用,那麽ref指向的是最外層容器組件實例而非包裹組件。
最好不用ref,使用狀態提升傳遞props是更好的選擇;確實需要時可以考慮React.forwardRef;

React.forwardRef

高階組件中,通過組件向一個後代組件傳遞ref,從而能夠訪問到該子組件(與標準數據流相反);

 使用rc-form增強的Form組件

解決方案:rc-form
詳情鏈接

Note: use wrappedComponentRef instead of withRef after [email protected]

class Form extends React.Component { ... }

// deprecated
    const EnhancedForm = createForm({ withRef: true })(Form);
    <EnhancedForm ref="form" />
    this.refs.form.refs.wrappedComponent // => The instance of Form

// Recommended
    const EnhancedForm = createForm()(Form);
    <EnhancedForm wrappedComponentRef={(inst) => this.formRef = inst} />
    this.formRef // => The instance of Form

需要引入‘rc-form‘模塊中的createForm方法;

antd中經過Form.create()增強的Form組件

類似rc-form,同樣使用wrappedComponentRef

經過 Form.create 之後如果要拿到 ref,可以使用 rc-form 提供的 wrappedComponentRef

class CustomizedForm extends React.Component { ... }

    // use wrappedComponentRef
    const EnhancedForm =  Form.create()(CustomizedForm);
    <EnhancedForm wrappedComponentRef={(form) => this.form = form} />
    this.form // => The instance of CustomizedForm
    const EnhancedForm = Form.create()(MyForm);
    const Parent extends Component {
    //父組件中引入EnhancedForm後,通過this.form可以訪問EnhancedForm子組件

    handleSubmit = () => {
         //handleOk是子組件的內部方法,可能包含驗證和提交處理數據等功能;
        this.form.handleOk();
    }
    render() {
        return (
            <EnhancedForm wrappedComponentRef = {(form) => this.form = form} />
            <Button onClick={ this.handleSubmit}/>
        )
    }

}

React-父組件訪問子組件內部