写在前面
- 前几天写过一篇文章:alita中组件的自定义与组件的再封装,但是在开发过程中发现那个方法不够规范。
- 那么本文我将详细讲一讲我认为规范的封装。
- 当然你要读懂本文,你需要结合alita中组件的自定义与组件的再封装一起看,因为本文是在其基础上的讲解。
开始
首先说明:
src/pages/test/components/index.tsx
为定义组件文件。
src/pages/test/index.tsx
为调用文件。
自定义组件
src/pages/test/components/index.tsx
import React, { FC } from 'react';
import { Button } from 'antd-mobile';
// 这里定义属性
interface TestProps {
type1?: string;
type2?: string;
text1?: string;
text2?: string;
onClick1?: (event) => void;
onClick2?: (event) => void;
}
const Test: FC<TestProps> = ({ type1, type2, text1='按钮1', text2='按钮2', onClick1 = () => {}, onClick2 = () => {} }) => {
return (
<>
<Button type={ type1 } onClick={ onClick1 }>{ text1 }</Button>
<Button type={ type2 } onClick={ onClick2 }>{ text2 }</Button>
</>
);
};
export default Test;
注意:这里我们可以给属性设置默认值(如上面的text1
和text2
)。
调用自定义组件
使用默认值
src/pages/test/index.tsx
import React, { FC, useEffect } from 'react';
import { IndexModelState, ConnectProps, connect } from 'alita';
// 导入自定义的组件
import Test from './components/index';
...;
const IndexPage: FC<PageProps> = ({ index, dispatch }) => {
...;
return (
// 这里就是封装好的组件,调用方法和我们平时使用的组件一样
// 我们什么参数都不传递
<Test />
);
};
export default connect(({ index }: { index: IndexModelState }) => ({ index }))(IndexPage);
这里我们什么参数都没有传递,来看看效果:
可以看到按钮的文字使用了默认值。
用户自定义值
src/pages/test/index.tsx
const IndexPage: FC<PageProps> = ({ index, dispatch }) => {
...;
return (
// 这里就是封装好的组件,调用方法和我们平时使用的组件一样
// 传递部分参数
<Test type1="warning" type2="primary" text1="btn1" text2="btn2" onClick1={() => { alert('123'); }}/>
);
};
现在看看效果:
点击按钮1:
好啦,现在已经讲解完毕了,相信大家对它的使用有了一定的了解,自己去尝试一下,会有不同的感觉哦。