我们上一节封装了一个按钮,这一节我们继续理解封装的概念和了解封装组件需要注意的事项
首先我们回顾上一篇最后的代码,代码如下
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’}) 进行创建,其实我们发现 Button 和 button 或者和 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 的语法