关键点: 1. 父组件onUserNameChange={(value) => onUserNameChange(value)}
2.子组件在子组件中通过回调的方式,将值传递给父组件onUserNameChange(value);
- 子组件添加value和onChange,将input变为有状态组件(有点像vue中的双向绑定)
import { Input } from "antd";
import React, { useState } from "react";
const UserNameInput = (props) => {
const { onUserNameChange } = props;
const [useNameValue, setUserNameValue] = useState();
const onInputChange = (e) => {
// Input不是直接是value,要看antd组件库中各组件的属性
const { value } = e.target;
// console.log(value, "children value");
// 将值传给父组件的回调函数
onUserNameChange(value);
// 将该组件变为有状态组件,useNameValue改变,组件重新渲染
setUserNameValue(value);
};
return <Input value={useNameValue} onChange={onInputChange} />;
};
export default UserNameInput;
export { UserNameInput };
- 父组件回调函数接收子组件传过来的值,并将值塞进form表单中,实现父子组件通信
import React from "react";
import ReactDOM from "react-dom";
import { UserNameInput } from "./UserNameInput.js";
import "antd/dist/antd.css";
import "./index.css";
import { Form, Input, Button, Checkbox } from "antd";
const Demo = () => {
const [basicForm] = Form.useForm();
const onLogin = (values) => {
basicForm
.validateFields()
.then((values) => {
console.log("Success:", values);
})
.catch((errorInfo) => {
console.error(errorInfo);
});
};
const onFinishFailed = (errorInfo) => {
console.log("Failed:", errorInfo);
};
const onUserNameChange = (value) => {
// console.log(value, "father value");
// 将值给form组件
basicForm.setFieldsValue({ username: value });
};
return (
<Form
name="basic"
form={basicForm}
onFinish={onLogin}
onFinishFailed={onFinishFailed}
>
<Form.Item
label="Username"
name="username"
rules={[
{
required: true,
message: "Please input your username!"
}
]}
>
<UserNameInput onUserNameChange={(value) => onUserNameChange(value)} />
</Form.Item>
<Form.Item
wrapperCol={{
offset: 8,
span: 16
}}
>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};
ReactDOM.render(<Demo />, document.getElementById("container"));