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> |
代码演示
- React
- Vue
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>
);
};
device/useScanCode/index
<template>
<demo-content>
<nut-button
shape="square"
type="primary"
class="gap"
block
@click="handleScan()"
>普通扫码</nut-button
>
<nut-button
shape="square"
type="primary"
class="gap"
block
@click="handleCameraScan()"
>相机扫码</nut-button
>
<nut-button
shape="square"
type="primary"
class="gap"
block
@click="handleScan('qrCode')"
>扫二维码</nut-button
>
</demo-content>
</template>
<script setup lang="ts">
import { useScanCode, useModal } from 'taro-hooks';
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 });
};
</script>
Hook 支持度
微信小程序 | H5 | ReactNative |
---|---|---|
✔️ | ✔️ | ✔️ |