当前位置: 首页 > news >正文

React TypeScript 定义组件的各种方式

目录

  • 举例说明
  • 1. 使用 class 定义
  • 2. 使用函数定义
    • 2.1 使用普通函数
    • 2.2 使用函数组件

举例说明

比如我们要定义一个计数器 Counter,它包含一个 label 和一个 button,计数器的初始值由外部传入,点击 button 计数加 1:

在这里插入图片描述

这虽然是个简单组件,但却包含了 React 定义组件的两大核心点:

  1. 属性由外部传入
  2. 状态由内部控制

组件样式:

// counter样式
const counterStyle = {backgroundColor: "orange",width: "100px",height: "100px",borderRadius: "10px",display: "flex",flexDirection: "column",alignItems: "center",justifyContent: "center",
} as React.CSSProperties;

使用组件:

<Counter initialCount={6} />

1. 使用 class 定义

// 属性
type Props = {// 初始countinitialCount: number;
};// 状态
type State = {count: number;
};// 计数器
class Counter extends Component<Props, State> {constructor(props: Props) {super(props);this.state = {count: props.initialCount,};}render() {return (<div style={counterStyle}><p>count={this.state.count}</p><buttononClick={() => {this.setState({count: this.state.count + 1,});}}>1</button></div>);}
}

2. 使用函数定义

2.1 使用普通函数

// 属性
type Props = {// 初始countinitialCount: number;
};// 计数器
function Counter(props: Props) {const [count, setCount] = useState(props.initialCount);return (<div style={counterStyle}><p>count={count}</p><buttononClick={() => {setCount(count + 1);}}>1</button></div>);
}

注:此函数返回的类型是 JSX.Element

2.2 使用函数组件

// 属性
type Props = {// 初始countinitialCount: number;
};// 计数器
const Counter = (props: Props) => {const [count, setCount] = useState(props.initialCount);return (<div style={counterStyle}><p>count={count}</p><buttononClick={() => {setCount(count + 1);}}>1</button></div>);
};

注:此函数返回的类型是 JSX.Element
若需要,可以指定函数返回的具体类型:

// 属性
type Props = {// 初始countinitialCount: number;
};// 计数器
const Counter: React.FC<Props> = (props) => {const [count, setCount] = useState(props.initialCount);return (<div style={counterStyle}><p>count={count}</p><buttononClick={() => {setCount(count + 1);}}>1</button></div>);
};

此时函数的返回值类型是 React.FC<Props>

http://www.lryc.cn/news/171351.html

相关文章:

  • 互联网摸鱼日报(2023-09-20)
  • AWS入列CNCF基金会
  • 岭回归与LASSO回归:解析两大经典线性回归方法
  • 数学建模——微分方程介绍
  • Minio入门系列【7】Spring Boot集成Minio
  • 抖音视频下载.py(23年9月份可用)
  • 项目基本搭建流程
  • 学习pytorch11 神经网络-非线性激活
  • Jenkins学习笔记2
  • 自动化测试:yaml结合ddt实现数据驱动!
  • 高效管理,轻松追踪——Chrono Plus for Mac任务管理工具
  • python项目2to3方案预研
  • MongoDB 是什么和使用场景概述(技术选型)
  • 打印 pyspark.sql.dataframe.DataFrame 有哪些列
  • 什么是虚拟DOM(Virtual DOM)?它在前端框架中的作用是什么?
  • QT实现简易时钟
  • win禁用更新,取消windows更新提示,禁用windows自动更新
  • 倒计时列表实现(小程序端Vue)
  • ContentType:application/x-www-form-urlencoded请求方法遇到的坑【PHP】
  • RabbitMQ - 死信、TTL原理、延迟队列安装和配置
  • 大数据与云计算实验一
  • 实施主品牌进化战略(一):确立主品牌进化架构
  • linux搭建单机ES,集成ik分词器,文本抽取,Kibana可视化平台
  • 金融和大模型的“两层皮”问题
  • 智能生活从这里开始:数字孪生驱动的社区
  • Python计算机二级知识点整理
  • 双系统ubuntu20.04(neotic版本)从0实现Gazebo仿真slam建图
  • (JavaEE)(多线程案例)线程池 (简单介绍了工厂模式)(含经典面试题ThreadPoolExector构造方法)
  • 单播与多播mac地址
  • 反向动力学Ik学习