鍍金池/ 問答/HTML/ react antd 中使用modal內嵌表單,但是使用ref取不到modal內

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)
        //打開模態(tài)框,清空表單
        // 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},為什么獲取不到這個組件?

回答
編輯回答
殘淚

生命周期不對。
didMount中,連Modal都沒有渲然完,哪來的refs?

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

2018年2月23日 19:47