react atnd函数式组件
背景
一句话: 函数式组件获取了render时所需要的值
react hooks 是 React 16.8 的新增特性。 它可以让我们在函数组件中使用 state 、生命周期以及其他 react特性,而不仅限于 class 组件。react hooks 的出现,标示着 react中不会在存在无状态组件了,只有类组件和函数组件。具体可查看官网。
优势:
函数组件不能使用state,遇到交互更改状态等复杂逻辑时不能更好地支持,hooks让函数组件更靠近class组件,拥抱函数式编程。
解决副作⽤问题,hooks出现可以处理数据获取、订阅、定时执行任务、手动修改 ReactDOM这些⾏为副作用,进行副作用逻辑。比如useEffect。
更好写出有状态的逻辑重用组件。
让复杂逻辑简单化,比如状态管理:useReducer、useContext。
函数式组件比class组件简洁,开发的体验更好,效率更⾼,性能更好。
更容易发现无用的状态和函数。
查阅
8 函数组件
- forwardRef
父组件想拿到子组件的 ref,使用 antd 的 Form.create() 包装子组件以后,
能够经过包装后的组件的 wrappedComponentRef 拿到子组件的实例。
可是由于子组件是一个 function component 没有实例,
致使不能在子组件上使用 wrappedComponentRef 属性
ref 转发:使用 React.forwardRef 函数包装一下 function component
React.forwardRef((prop,ref)=>{function component}) 复制代码 - useRef
- useState
代码实现
- 子组件
import React, { useImperativeHandle } from "react";
import { Form, Input, Modal } from "antd";
const CreateForm = Form.create({
name: "createForm"
})(
React.forwardRef((props, ref) => {
const { visible, onCancel, onCreate, form } = props;
const { getFieldDecorator } = form;
useImperativeHandle(ref, () => ({
form
}));
return (
<div>
<Modal
title="Normal Form"
visible={visible}
onOk={onCreate}
onCancel={onCancel}
closable={false}
>
<Form>
<Form.Item label="name">
{getFieldDecorator("name", {
rules: [{ required: true, message: "Please type your name!" }]
})(<Input />)}
</Form.Item>
</Form>
</Modal>
</div>
);
})
);
export default CreateForm;
- 父组件
import React, { useState, useRef, useEffect } from "react";
import { Button, notification } from "antd";
import CreateForm from "./CreateForm";
const Landing = () => {
const [visible, setVisible] = useState(false);
const [activeForm, setActiveForm] = useState("normal");
const formRef = useRef(null);
const showForm = () => {
setVisible(true);
};
const changeForm = () => {
setActiveForm(prevState =>
prevState === "normal" ? "deprecated" : "normal"
);
};
useEffect(() => {
notification.open({
message: "Form Status",
description: activeForm
});
}, [activeForm]);
const handleCancel = () => {
setVisible(false);
};
const handleCreate = () => {
let form = formRef.current.form;
form.validateFields((err, values) => {
if (err) {
console.log("Error: ", values);
return;
}
console.log("Received values of form: ", values);
form.resetFields();
setVisible(false);
});
};
return (
<div>
<h1>Test</h1>
<Button type="primary" onClick={showForm} style={{ margin: "10px" }}>
Show form
</Button>
<Button type="primary" onClick={changeForm} style={{ margin: "10px" }}>
Change form
</Button>
<CreateForm
visible={visible}
onCancel={handleCancel}
onCreate={handleCreate}
wrappedComponentRef={formRef}
/>
</div>
);
};
export default Landing;
本文来自博客园,作者:vx_guanchaoguo0,转载请注明原文链接:https://www.cnblogs.com/guanchaoguo/p/16145574.html