【react】类组件与函数组件 ref 通信

类组件与函数组件 ref 通信
本篇文章主要针对于react 16版本以上用法

1、创建ref 实例

   constructor(props) {
        super(props);
        this.state ={
            tags:[],
            actionTag:'',//点击的实体名称
            tagindex:0,
            submenu:[],
            NewAttr:[],//添加的空白属性
          };
        this.myRef = React.createRef(); //重点
    }

2、第二步 ,给组件传递ref

{entity !== undefined ? <Myinput attr={entity} tagName={actionTag} getlatestData={this.getlatestData} getEntityAttr={this.getEntityAttr} formRef={this.myRef} /> : null}

3、第三步,将ref传递给函数组件里面的form

  if (props.attr !== undefined) {

    arr = props.attr;
    arr.forEach(item => {
      initValues[item.label] = item.value;
    })
  }

  return (
    <Row>
      <Col span={24} style={{ maxHeight: 400, overflow: 'hidden', overflowY: 'auto' }}>
        <Form onFinish={onFinish} onFinishFailed={onFinishFailed} initialValues={initValues} {...layout} form={form} ref={props.formRef}>  //这一块将ref传递给form表单是为了获取form实例
          {
            arr.length > 0 ? arr.map((item, key) => {
              return <Form.Item label={item.name} name={item.label} key={key}>
                <Input width={200} />
              </Form.Item>
            }) : null
          }

        </Form>

      </Col>
      <Col span={24} style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', marginTop: '10px' }}>
        <Button type="primary" onClick={handleSubmit}> 提交</Button>
      </Col>
    </Row>
  )
}

4、第四步,在父组件中获取form表单实例,并调用其方法

//SearchEntityAttr是我封装的请求,拿到数据后重置子组件form表单实例,重新初始化表单默认值
 SearchEntityAttr(data).then(res => {
      //  console.log(res);
      if (res.data.code === 0) {
        this.setState({
          entity: res.data.data.props
        }, () => {
          this.myRef.current.resetFields();
        })
      } else {
        message.error(res.data.msg)
      }
    })

参考:https://blog.csdn.net/yang423712/article/details/117930596

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值