类组件与函数组件 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.youkuaiyun.com/yang423712/article/details/117930596