UNPKG

@nutui/nutui-react-taro

Version:

京东风格的轻量级移动端 React 组件库,支持一套代码生成 H5 和小程序

76 lines (75 loc) 3.31 kB
import React, { useImperativeHandle, useRef } from "react"; import { createSelectorQuery, getEnv, useReady, useUnload } from "@tarojs/taro"; import lottie from "@nutui/lottie-miniprogram"; import { getWindowInfo } from "../../utils/get-system-info"; import useUuid from "../../hooks/use-uuid"; export var Lottie = /*#__PURE__*/ React.forwardRef(function(props, ref) { var uuid = useUuid(); var id = "nutLottie-".concat(uuid); var animation = useRef(); var inited = useRef(false); var source = props.source, _props_loop = props.loop, loop = _props_loop === void 0 ? true : _props_loop, _props_autoPlay = props.autoPlay, autoPlay = _props_autoPlay === void 0 ? true : _props_autoPlay, onComplete = props.onComplete, style = props.style, _props_speed = props.speed, speed = _props_speed === void 0 ? 1 : _props_speed; var setSpeed = function() { if (animation.current) { animation.current.setSpeed(Math.abs(speed)); animation.current.setDirection(speed > 0 ? 1 : -1); } }; useImperativeHandle(ref, function() { return animation.current || {}; }); var dpr = useRef(getWindowInfo().pixelRatio); useReady(function() { createSelectorQuery().select("#".concat(id)).fields({ node: true, size: true }, function(res) { try { var canvas = res.node; var context = canvas.getContext('2d'); // scale canvas to adapt dpr if (style && style.width !== undefined && style.height !== undefined) { canvas.width = parseFloat(style.width.toString()) * dpr.current; canvas.height = parseFloat(style.height.toString()) * dpr.current; context.scale(dpr.current, dpr.current); } lottie.setup(canvas); animation.current = lottie.loadAnimation({ animationData: source, loop: loop, autoplay: autoPlay, rendererSettings: { context: context } }); onComplete && animation.current.addEventListener('complete', onComplete); setSpeed(); inited.current = true; } catch (error) { console.error(error); } }).exec(); }); useUnload(function() { onComplete && animation.current && animation.current.removeEventListener('complete', onComplete); animation.current && animation.current.destroy(); }); return getEnv() === 'WEAPP' || getEnv() === 'JD' ? /*#__PURE__*/ React.createElement("canvas", { id: id, // @ts-ignore // eslint-disable-next-line react/no-unknown-property canvasId: id, // eslint-disable-next-line react/no-unknown-property disalbeScroll: true, type: "2d", style: style }) : /*#__PURE__*/ React.createElement("canvas", { id: id, // eslint-disable-next-line react/no-unknown-property "canvas-id": id, // eslint-disable-next-line react/no-unknown-property "disalbe-scroll": true, style: style }); }); Lottie.displayName = 'NutLottie';