惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
博客园 - 三生石上(FineUI控件)
爱范儿
爱范儿
Vercel News
Vercel News
aimingoo的专栏
aimingoo的专栏
The GitHub Blog
The GitHub Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
A
About on SuperTechFans
H
Hackread – Cybersecurity News, Data Breaches, AI and More
量子位
Hugging Face - Blog
Hugging Face - Blog
C
Check Point Blog
Engineering at Meta
Engineering at Meta
有赞技术团队
有赞技术团队
月光博客
月光博客
M
MIT News - Artificial intelligence
V
Visual Studio Blog
Stack Overflow Blog
Stack Overflow Blog
阮一峰的网络日志
阮一峰的网络日志
D
DataBreaches.Net
I
InfoQ
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Cloudflare Blog
雷峰网
雷峰网

Li Hui Blog

工作流调研与实践经验 如何搭建私有仓库 Nexus 并配置 SSL 证书 从零开始搭建单节点 ELK 浅谈一个产品的用户引导 归档 GoCD 加入基础密码验证 搭建一套 gocd 的环境 如何使用 gitbook cli工具 React 组件示例 如何搭建第一个 React 程序 [SpringBoot 指南] 连接 mysql 数据库并进行增删改查测试 [SpringBoot 指南] 如何开始 Springboot 之旅 实现自己第一个接口 LeetCode刷题笔记 VPC笔记 读书的目的 [人文书籍] 把时间当作朋友 Docker基础命令 [技术书籍]JSON必知必会 Docker原理研究 使用Ubuntu 及宝塔搭建Ghost平台 [Linux]Ubuntu安装宝塔面板 2020年年终总结 CURL学习教程 2020年度计划记录 [安全系列]生成ssh证书 [CLI应用学习]时间使用GitHub CLI [linux系列] 修改主机用户名 轻松学CLI应用总章节 [Shell编程系列]基础教程2 [Shell编程系列]基础教程1
React JSX语法再实践
2022-01-07 · via Li Hui Blog

我们上一节封装了一个按钮,这一节我们继续理解封装的概念和了解封装组件需要注意的事项

首先我们回顾上一篇最后的代码,代码如下

 1const Button = ({color,text}) =>{
 2    return {
 3        type: 'button',
 4        props: {
 5            className: `btn btn - $ {
 6                color
 7            }`,
 8            children: {
 9                type: 'em',
10                props: {
11                    children: text,
12                },
13            },
14        },
15    };
16}

我们最终调用的形式如下所示 Button({color:‘blue’, text:‘Confirm’}) 进行创建,其实我们发现 Buttonbutton 或者和 em 一样都可以 作为一个元素存在,我们可以以 Button 为基础创建特定属性的按钮,将其称为自定义类型的元素 或者可以称为组件元素。和上一节相同,我们可以采用 JSON 结构来描述它

1{
2 type: Button,
3 props: {
4  color: 'blue',
5  children: 'Confirm'
6 }
7}

上述结构和我们文中的第一个结果,因此可以进一步的对其中的元素做封装

比如我们对通常使用警告的颜色为红色, 但是我们红色提示的文字可能不同,此处我们封装一个危险的按钮的示例

1const dangerButton =({text}) => ({
2  type: Button,
3  props: {
4    color: 'red',
5    children: text  
6}
7})

比如书中给了一个很好的示例

 1const DeleteAccount = () = >({
 2    type: 'div',
 3    props: {
 4        children: [{
 5            type: 'p',
 6            props: {
 7                children: 'Are you sure?',
 8            },
 9        },
10        {
11            type: DangerButton,
12            props: {
13                children: 'Confirm',
14            },
15        },
16        {
17            type: Button,
18            props: {
19                color: 'blue',
20                children: 'Cancel',
21            },
22        }],
23    }
24});

这是一个弹出的删除账户的组件,其中有文字以及确定和取消的按钮,删除账户的组件就完成了。

我们后面将继续介绍 JSX 的语法