react-native的阴影实现,兼容android和ios

2022-09-08  本文已影响0人  sunny635533

效果:


image.png
import PropTypes from 'prop-types';
import React from 'react';
import {
    View,
    Dimensions,
    StyleSheet,
    Platform,
} from 'react-native';

const ShadowCard = props => {
    const { children, elevation, opacity, cornerRadius } = props;

    const cardStyle = Platform.select({
        ios: () =>
            StyleSheet.create({
                container: {
                    shadowRadius: elevation,
                    shadowOpacity: opacity,
                    shadowOffset: { width: 0, height: elevation },
                    borderRadius: cornerRadius,
                    backgroundColor: props.backgroundColor,
                    width: Dimensions.get('window').width - 40,
                }
            }),
        android: () =>
            StyleSheet.create({
                container: {
                    elevation: elevation,
                    borderRadius: cornerRadius,
                    backgroundColor: props.backgroundColor,
                    width: Dimensions.get('window').width - 40,
                }
            })
    })();

    return (
        <View style={[cardStyle.container, props.style]}>
            {children}
        </View>
    )

}

ShadowCard.prototype = {
    backgroundColor: PropTypes.string,
    elevation: PropTypes.number,
    cornerRadius: PropTypes.number,
    opacity: PropTypes.number
}

ShadowCard.defaultProps = {
    backgroundColor: '#ffffff',
    elevation: 3,
    cornerRadius: 5,
    opacity: .5
}

export default ShadowCard

使用方式如下:

<ShadowCard style={{
          margin: 5,
          elevation: 24,
          shadowRadius: 24,
          shadowOffset: {
            width: 0,
            height: 8
          },
          shadowColor: 'red',//"rgba(138, 160, 181, 0.24)"
        }}>
          <Text style={{ color: 'red' }}>Open up App.js to start working on your app!</Text>
          <Text>Changes you make will automatically reload.</Text>
          <Text>Shake your phone to open the developer menu.</Text>
        </ShadowCard>
        <ShadowCard style={{ padding: 10, margin: 10 }}>
          <Text>Shake your phone to open the developer menu.</Text>
        </ShadowCard>
        <ShadowCard style={{ padding: 10, margin: 10, height: 50, width: 100 }}>
        </ShadowCard>
上一篇 下一篇

猜你喜欢

热点阅读