Antd之Modal+Form

在react+antd的前端开发中少不了使用Modal+Form的形式来实现添加/编辑等功能!

本文主要记录在使用antd4.9.2开发过程中经常遇到的问题:this.formRef.current为空的情况!

首先需要验证一个机制就是当Modal默认visible=false的时候不会去渲染Modal下的组件

class Test extends Component{
    constructor(props) {
        super(props);
        this.formRef = React.createRef()
        this.state = { show: false}
        console.log('Test.constructor')
    }
    render() {
        return (
            <Modal visible={this.state.show}>
                <Home/>
                <Form ref={this.formRef}>
                </Form>
             </Modal>)
    }
}

class Home extends Component{
    constructor(props) {
        super(props);
    
        console.log('Home.constructor ')
    }
    render() {
        return (
         <div>hello world!</div>)
        }
    }
}

上述代码默认Modal是不显示的,第一次运行的时候console打印日志为

Test.constructor

当默认Modal为显示的时候,第一次运行的时候console打印日志为

Test.constructor
Home.constructor

所以很多时候需要在componentWillReceiveProps中对Form表单进行操作比如重置表单默认数据时,很可能会因为this.formRef.current还没有被初始化而导致的异常,代码如下

componentWillReceiveProps(nextProps) {
        
     this.formRef.current.resetFields();
                
}

解决方案如下代码,在setState()的回调函数中去操作,setState的回调函数表示已经执行了render完毕,所以这时this.formRef.current肯定是初始化过了的

componentWillReceiveProps(nextProps) {
this.setState({
    show: nextProps.show,
    value: nextProps.value
    },
    () => {
        if(this.formRef.current)
        {
            this.formRef.current.resetFields();
        }
    })
}

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值