父组件数据变化,子组件数据更新方法:
利用componentWillReceiveProps方法
componentWillReceiveProps(nextProps){
this.setState({
isLogin: nextProps.isLogin,
userInfo: nextProps.userInfo,
});
}
子组件数据变化,通知父组件
// 父组件:
<FromCom demo={this.demo} />
//子组件:利用setState的回调函数
this.setState({}, () => {
this.props.demo(userInfo);
});
实例
import "../static/css/login.scss";
import React, { Component, useState, useEffect } from "react";
import { Form, Input, InputNumber, Button, Tabs } from "antd";
import { UserOutlined } from "@ant-design/icons";
const { TabPane } = Tabs;
export default class FormPage extends Component {
constructor() {
super();
this.state = {
isLogin: true,
userInfo: {
name: "",
password: "",
},
};
}
callback = () => {
this.setState({
isLogin: !this.state.isLogin,
userInfo: {
name: "",
password: "",
},
});
};
demo=(val)=>{
console.log("=============>子组件传递的参数")
}
render() {
const { isLogin, userInfo } = this.state;
return (
<div className="login">
<Tabs defaultActiveKey="1" onChange={this.callback} size="large">
<TabPane tab="登录" key="1"></TabPane>
<TabPane tab="注册" key="2"></TabPane>
</Tabs>
<FromCom isLogin={isLogin} demo={this.demo} userInfo={userInfo} />
</div>
);
}
}
class FromCom extends Component {
constructor(props) {
super(props);
this.state = {
...props
};
}
componentWillReceiveProps(nextProps){
this.setState({
isLogin: nextProps.isLogin,
userInfo: nextProps.userInfo,
});
}
submit = () => {
const { userInfo, isLogin } = this.state;
// 子组件改变传递给父组件采用setState的回调函数
this.setState({}, () => {
this.props.demo(userInfo);
});
if (isLogin) {
console.log("=============>登录", userInfo);
} else {
console.log("=============>注册", userInfo);
}
};
render() {
const { userInfo, isLogin } = this.state;
return (
<div>
<div>
<Form
name="basic"
labelCol={{
span: 4,
}}
wrapperCol={{
span: 20,
}}
autoComplete="off"
>
<Form.Item label="用户名">
<Input
onChange={(e) => {
this.setState(() => (userInfo.name = e.target.value));
}}
value={userInfo.name}
size="large"
placeholder="请输入用户名"
prefix={<UserOutlined />}
/>
</Form.Item>
<Form.Item label="密码">
<Input
onChange={(e) => {
this.setState(() => (userInfo.password = e.target.value));
}}
value={userInfo.password}
size="large"
placeholder="请输入密码"
prefix={<UserOutlined />}
/>
</Form.Item>
<Form.Item>
<Button type="primary" onClick={this.submit}>
{isLogin ? "登录" : "注册"}
</Button>
</Form.Item>
</Form>
</div>
</div>
);
}
}