Taro react 插件提供外部插件引用
项目结构
projectName
|-pages/index
|-plugin
|-components
|-avatar
index.config.ts
export default { navigationBarTitleText: '首页', usingComponents: { 'avatar': 'plugin://myPlugin/avatar' } }
index页面中引用:
import Taro from '@tarojs/taro' import { Component, PropsWithChildren } from 'react' import { View, Text, Navigator } from '@tarojs/components' import './index.less' const myPluginInterface = Taro.requirePlugin('myPlugin') export default class Index extends Component<PropsWithChildren> { // state: { // avatarUrl: 'http://storage.360buyimg.com/taro-static/static/images/logo.png' // } componentDidMount () { myPluginInterface.sayHello() const answer = myPluginInterface.answer console.log('answer: ', answer) } componentWillUnmount () { } componentDidShow () { } componentDidHide () { } render () { // let avatarUrl = 'http://storage.360buyimg.com/taro-static/static/images/logo.png' // let { avatarUrl } = this.state const avatarProps = { src: 'http://storage.360buyimg.com/taro-static/static/images/logo.png', width: 500, height: 500, } return ( <View className='index'> <Text>Hello world!</Text> <avatar props={avatarProps} /> <Navigator url='plugin://myPlugin/list'> Go to pages/list! </Navigator> </View> ) } }
avatar组件FC方式定义:
import { useEffect, useState } from 'react' import { View, Image } from '@tarojs/components' import { getPageBottom } from '@/core' import { useLoad } from '@tarojs/taro' import './avatar.less' interface Props{ src?: string width?: number height?: number } export default function Avatar({ src = '', width = 100, height = 100 }: Props) { const [ avatarStyle, setAvatarStyle ] = useState({}) useLoad(() => { // let obj = getPageBottom(); // setPaddingTop(obj.pix * top) // setAvatarStyle({ // width: width * obj.pix, // height: height * obj.pix, // }) }) useEffect(() => { let obj = getPageBottom(); // setPaddingTop(obj.pix * top) setAvatarStyle({ width: width * obj.pix, height: height * obj.pix, }) }, [width, height]) return ( <View className='M-Avatar' style={avatarStyle}> <Image className='image' src={src} /> </View> ) }
或者Component方式定义:
import { Component, ReactNode } from 'react' import { View, Image } from '@tarojs/components' import { getPageBottom } from '@/core' type Props<P = unknown> = P & { children?: ReactNode | undefined src?: string width?: number height?: number } export default class Avatar extends Component<Props> { constructor(props) { super(props); console.log('Avatar', props) } render () { const { src = '', width = 100, height = 100 } = this.props let obj = getPageBottom(); const avatarStyle = { width: width * obj.pix, height: height * obj.pix, } return ( <View className='M-Avatar' style={avatarStyle}> <Image className='image' src={src} /> </View> ) } }
avatar.less
.M-Avatar { width: 100rpx; height: 100rpx; border-radius: 50%; overflow: hidden; .image { width: 100%; height: 100%; } }