跳到主要内容

useScanCode

扫码

何时使用

当需要针对维码进行解析时

API

const { scan, cameraScan } = useScanCode(initialOption?: Option);

参数说明

参数说明类型默认值
onlyFromCamera是否只能从相机扫码,不允许从相册选择图片boolean-
scanType扫码类型ScanType-

返回值说明

返回值说明类型
scan扫码(options?: Options) => Promise<scanCode.SuccessCallbackResult>
cameraScan相机扫码(scanType?: keyof scanCode.ScanType) => Promise<scanCode.SuccessCallbackResult>

代码演示

device/useScanCode/index
import React from 'react';
import { useScanCode, useModal } from 'taro-hooks';
import DemoContent from '@src/components/DemoContent';
import { Button } from '@taroify/core';

export default () => {
const { scan, cameraScan } = useScanCode();
const show = useModal({ mask: true, title: '扫码结果', showCancel: false });

const handleScan = async (scanType?) => {
let content = '';
try {
const res = await scan({ scanType });
content = JSON.stringify(res);
} catch (e) {
content = e.errMsg || e.message;
}
show({ content });
};

const handleCameraScan = async () => {
let content = '';
try {
const res = await cameraScan();
content = JSON.stringify(res);
} catch (e) {
content = e.errMsg || e.message;
}
show({ content });
};

return (
<DemoContent>
<Button
block
color="primary"
className="gap"
onClick={() => handleScan()}
shape="square"
>
普通扫码
</Button>
<Button
block
color="primary"
className="gap"
onClick={() => handleCameraScan()}
shape="square"
>
相机扫码
</Button>
<Button
block
color="primary"
className="gap"
onClick={() => handleScan('qrCode')}
shape="square"
>
扫二维码
</Button>
</DemoContent>
);
};

Hook 支持度

微信小程序H5ReactNative
✔️✔️✔️