函数组件
函数组件是使用函数定义的 React组件 ,它们本质上是无状态的,只通过props 接受数据,并返回 JSX 作为输出。
在 React 16.8 之前,函数组件主要用于不涉及状态或生命周期的简单UI渲染。React 16.8 版本引入了 Hooks,使得函数组件能够使用状态和其他React特性,如 useState 和 useEffect,这极大地增强了函数组件的能力,这使得函数组件在 React 开发中愈发流行和广泛使用。
特点
- 使用函数定义组件,使用更简单
- 无法直接使用 this,通过 hooks 来管理状态和副作用
- 通常用于无状态组件,有状态需求时需要使用 hooks
语法
type IProps = {
name: string;
};
function HelloFunction(props: IProps) {
return (
<div>
Hello {props.name}
</div>
);
}
export default HelloFunction;
函数类型约束
import React from "react";
type IProps = {
name: string;
};
const HelloFunction: React.FC<IProps> = (props) => {
return (
<div>
Hello {props.name}
</div>
);
}
export default HelloFunction;
内部状态
函数组件中使用 useState 定义响应式变量
import React, { useState } from "react";
type IProps = {};
const HelloFunction: React.FC<IProps> = (props) => {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(count + 1)}>
child count is {count}
</button>
</div>
);
}
export default HelloFunction;
组件传参
函数组件接收外部传参与class组件类似
import React, { useEffect, useState } from "react";
type IProps = {
name: string;
};
const HelloFunction: React.FC<IProps> = (props) => {
return (
<div>Hello {props.name}</div>
);
}
export default HelloFunction;
生命周期
函数组件本质没有生命周期,但是我们通过hooks来模仿类组件当中的 componentDidMount 生命周期
import React, { useEffect, useState } from "react";
type IProps = {};
const HelloFunction: React.FC<IProps> = (props) => {
useEffect(() => {
console.log("类似 componentDidMount");
return () => {
console.log("类似 componentWillUnmount");
};
}, []);
return (
<div />
);
}
export default HelloFunction;
当组件被加载后会调用 useEffect 副作用起到组件挂载生命周期的作用。
监听参数变化
import React, { useEffect, useState } from "react";
type IProps = {
name: string;
};
const HelloFunction: React.FC<IProps> = (props) => {
useEffect(() => {
console.log("props.name 改变", props.name);
}, [props.name]);
return (
<div>Hello {props.name}</div>
);
}
export default HelloFunction;
// 父组件调用
<HelloFunction name={count.toString()} />
// 初始化默认也会调用
// props.name 改变 0
// props.name 改变 1
// props.name 改变 2
参考
友情提示
见原文:【React】函数组件)
本文同步自微信公众号 "程序员小溪" ,这里只是同步,想看及时消息请移步我的公众号,不定时更新我的学习经验。