分享一个box-shadow阴影组件封装,可自动适应内容宽高。
首先要安装react-native-shadow
yarn add react-native-shadow
然后安装一个react-native-svg,注意要去github上看下版本对照表,要对应版本安装
yarn add react-native-svg
/yarn add react-native-svg@x.x.x
封装:
import React from 'react'
import {
ViewStyle
} from 'react-native'
import Base from '@/components/Base';
import { View } from '@/components';
import { BoxShadow as RNBoxShadow, BoxShadowType } from "react-native-shadow";
interface Props {
data?: any //用来控制重新渲染高度
style?: ViewStyle
color?: string
shadowOption?: {
border?: number; // the width of shadow , cannot less than 0
radius?: number; // the same value as the "borderRadius" of chileElement
opacity?: number; // the opacity of shadow
x?: number; // the offsetX of shadow
y?: number; // the offsetY of shadow
style?: ViewStyle; // the style you want to add to the wrapper box
}
children?: React.ReactNode;
}
interface State {
contentHeight: number
contentWidth: number
showShadow: boolean
}
/**
* box-shadow组件,包裹在需要阴影的View外
* @param {string} color 阴影颜色
* @param {Object} shadowOption 阴影配置
* @param {*} data 触发重新渲染的props,用来重新计算宽高
* **/
export default class BoxShadow extends Base<Props, State> {
public state: State = {
contentHeight: 0,
contentWidth: 0,
showShadow: false
};
public componentDidMount() {
}
public componentWillReceiveProps(nextProps:any) {
if(nextProps.hasOwnProperty('data') &&
JSON.stringify(this.props.data) != JSON.stringify(nextProps.data)
) {
// reRender
this.setState({
showShadow: false
})
}
}
render() {
const { color, style, shadowOption } = this.props;
if (!this.state.showShadow) {
return (
<View style={style}
onLayout={e => {
const layout = e.nativeEvent.layout
// console.log(layout)
this.setState({
contentWidth: layout.width,
contentHeight: layout.height,
showShadow: true
})
}}
>
{this.props.children}
</View>
)
}
return (
<RNBoxShadow
setting={{
height: this.state.contentHeight,
width: this.state.contentWidth,
color: color || '#000',
border: shadowOption?.border || 5,
radius: shadowOption?.radius || 5,
opacity: shadowOption?.opacity || 0.2,
x: shadowOption?.x || 0,
y: shadowOption?.y || 0,
style: shadowOption?.style || {},
}}
>
<View style={style}>
{this.props.children}
</View>
</RNBoxShadow>
);
}
}
export { BoxShadow };
使用:
import { BoxShadow, View, Text } from "@/components";
//...
render() {
const { info } = this.state
return (
<BoxShadow data={info} shadowOption={{
border: 10,
opacity: 0.5
}}>
<View style={{backgroundColor: '#fff'}}>
<Text>{info}</Text>
</View>
</BoxShadow>
)
}
网友评论