React-父组件访问子组件内部

父子组件通信

典型数据流:父组件向后代组件传递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}/>
        )
    }

}

猜你喜欢

转载自www.cnblogs.com/muTing/p/9503063.html