react antd 中使用modal内嵌表单,但是使用ref取不到modal内部的子DOM

首先是是一个父组件,里面包含一个modal

import React from 'react';
import { Button, Input, Table, Modal } from 'antd';

import ApplyCertificateForm from './components/apply-certificate-form';
import UploadCertificateFrom from './components/upload-certificate-form';

const Search = Input.Search;


export default class SecCertificateList extends React.Component{
    constructor(props){
        super(props);
        this.applyFormElement=React.createRef();
        this.aa="222222222";
    }
   
    state = {
        apply_visible: false,
        upload_visible:false
    };
    componentDidMount() {
        console.log('11111111111')
        console.log(this.applyFormElement);
    }
    showModal=(name,e)=>{
        let title=name+'_visible';
        this.setState({
            [title]:true,
        });
        console.log(this.applyFormElement)
        //打开模态框,清空表单
        // this.applyFormElement.current.resetFields();
    };
    handleCancel = (name,e) => {
        console.log(e);
        this.setState({
            [name+'_visible']: false,
        });
    };

    handleOk = (name,e) => {
        console.log(e);
        this.setState({
            [name+'_visible']: false,
        });
    }

    render(){
        return (
            <div>
                <Button type="primary" onClick={this.showModal.bind(this,'apply')}>申请证书</Button>
              
                <Modal
                    title="申请证书"
                    visible={this.state.apply_visible}
                    onOk={this.handleOk.bind(this,'apply')}
                    onCancel={this.handleCancel.bind(this,'apply')}
                    // footer={[
                    //     <Button key="back" onClick={this.handleCancel.bind(this,'apply')}>取消</Button>,
                    //     <Button key="submit" type="primary" onClick={this.handleOk.bind(this,'apply')}>
                    //         确认
                    //     </Button>,
                    // ]}
                    okText={'确认'}
                    cancelText={'取消'}
                    destroyOnClose={true}
                >
                    <div ref={this.applyFormElement}>11111111111{this.aa}</div>
                    <ApplyCertificateForm  ref={this.applyFormElement}/>
                </Modal>
            </div>
        )
    }
}

如代码所示,我在modal标签内,又加了一个<ApplyCertificateForm />,我希望在整个父组件中获取到他,但是我加上ref={this.applyFormElement},在 父组件

componentDidMount() {
        console.log('11111111111')
        console.log(this.applyFormElement);
    }

中打印出来的是{current:null},为什么获取不到这个组件?

阅读 13.4k
3 个回答

生命周期不对。
didMount中,连Modal都没有渲然完,哪来的refs?

你可以在ModalonOk事件中,获取一下看看能不能拿到。
另外stateless component是没有refs的。

新手上路,请多包涵

Modal和Dialog的didmount没有暴露给你, 所以setState visible的时候, 等下一个microTask里去做逻辑就可以了

新手上路,请多包涵

可以加个setTimeout在dom渲染完后处理

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题