父组件
handleOk = () => {
const changeValue = this.formRef.current.getFieldValue('categoryName')
// 取到子组件的输入框的值
}
render() {
return (
<Modal title={this.state.modalName}
visible={this.state.visible}
onOk={this.handleOk}
onCancel={this.hideModal}
>
<AddForm name={this.state.currentName}
setForm={(form) => this.formRef = form} // 这句话就是拿到子组件的form功能,传 递给一个变量 formRef,可以随意取名字
>
</AddForm>
</Modal>
)
}
其中 AddForm是子组件类
import React from 'react'
import { Form, Input } from 'antd';
export default class AddForm extends React.Component {
formRef = React.createRef();
UNSAFE_componentWillMount() {
this.props.setForm(this.formRef) // 把form的功能传递给父组件,setForm是父组件在传参时的函数名
}
show = () => {
setTimeout(()=>{ // 不然会取不到this.formRef.current的值报错
// 防止出先下一次弹窗的输入框的值还是上次的
this.formRef.current.setFieldsValue({
categoryName:this.props.name
})
})
}
render() {
this.show()
return (
<Form
ref={this.formRef} // 定义form
name="control-ref"
>
<Form.Item
label="分类名称"
name="categoryName"
>
<Input placeholder="请输入" style={{ width: 300 }}></Input>
</Form.Item>
</Form>
)
}
}
主要是记录怎么父组件和子组件的form传值,以及解决一个连续点开输入框的值不改变的问题:
这是问题复现
这是解决之后