想封装一个icon库(别问我为什么不用iconfont,彩色的),动态传入图片名称,代码如下
import React, { Component } from 'react'; import { View, Image} from 'react-native'; import icons from './icon' function BiconComponent(props){ return ( <View> <Image source={require(`./icon/${props.icon}.png`)} /> </View> ) } export default BiconComponent却无法渲染,控制台报错 想来我的代码页没什么问题啊,查了很多资料,知道了在RN中的require中的路径不能拼接。 好吧,只能在数据中require好了
接下来是设置icon大小了,因为我的图片都是宽高相同或宽比高大,所以我想,这还不简单,在html中给img外层高设置宽高,给图片设置宽度,高度不就自适应了吗? 理想是丰满的,然而现实却是骨感的
import React, { Component } from 'react'; import { View, Image} from 'react-native'; import icons from './icon' const styles = (props) =>{ let icon = icons[props.icon].icon let iconRW = Image.resolveAssetSource(icon).width let iconRH = Image.resolveAssetSource(icon).height let iconW = iconRW >= iconRH ? props.size*0.8 : (props.size * iconRW / iconRH)*0.8 let iconH = iconRH >= iconRW ? props.size*0.8 : (props.size * iconRH / iconRW)*0.8 console.log(iconW, iconH) return { container:{ width:props.size, height:props.size, paddingTop:(props.size*0.8-iconH)/2+0.1*props.size, paddingBottom:(props.size*0.8-iconH)/2+0.1*props.size, paddingLeft:(props.size*0.8-iconW)/2+0.1*props.size, paddingRight:(props.size*0.8-iconW)/2+0.1*props.size, backgroundColor:'#ececec', borderRadius:props.size*0.5 }, img:{ width: iconW, height: iconH } } } function BiconComponent(props){ let icon = icons[props.icon].icon console.log(styles(props), props) return ( <View style={styles(props).container}> <Image source={icon} style={styles(props).img} /> </View> ) } export default BiconComponent