首页 > 解决方案 > React Native,创建动态影子卡?

问题描述

我将如何创建一个视图,该视图将与“绝对位置”和 zIndex 略有偏移?我的目标是创建一个带有阴影的 3d 幻觉。

我可以通过创建 2 个相同的视图来做到这一点,但这也会在 "shadow" 中呈现 {props.children} ,只是为了保持与主视图相同的大小

任何人都知道如何在没有 {props.children} 的情况下克隆主视图任何指针将不胜感激!


const ShadowCardTest = props => {
    return (
        <View style={styles.cardContainer}>
            <View style={styles.shadowContainer}>
                    <View style={styles.card}>{props.children}</View> {/* MAIN VIEW*/}
                    <View style={styles.shadow}>{props.children}</View> {/* SHADOW VIEW*/}
            </View>
        </View>
    );
};

const styles = StyleSheet.create({
    cardContainer: {
        flex: 1,
        justifyContent: "center",
    },

    shadowContainer: {
        width: "85%",
        alignSelf: "center",
    },

    card: {
        backgroundColor: 'rgba(255,255,255,0.5)',
        borderRadius: 25,
        width: '100%',
        maxWidth: 500,
        padding: "6%",
        zIndex: 2,
    },

    shadow: {
        backgroundColor: 'rgba(0,0,0,0.1)',
        borderRadius: 25,
        width: '100%',
        maxWidth: 500,
        padding: "6%",
        position: "absolute",
        marginTop: "4%",
        marginLeft: "4%",
        zIndex: 1,
    },

})

export default ShadowCardTest;

编辑:

我解决了这个问题,并想尽可能地分解它。我使用 setState 来重新渲染视图,否则它将不起作用。

首先,我创建了一些状态来处理我通过使用 onLayout 获得想要阴影的卡片的大小。

const [height, setHeight] = useState(1);
const [width, setWidth] = useState(1);

const getCardSize = (event) => {
    const {x, y, height, width } = event.nativeEvent.layout;
    setHeight(height);
    setWidth(width);

以及以下内容:

<View style={styles.card} onLayout={getCardSize}>{props.children}</View>

有了这一切,我只是将它添加到我的“阴影视图”中

<View style={{...styles.shadow, ...{ width: width, height: height },}}></View>

我希望这可以帮助别人。

标签: react-native3dstyles

解决方案


推荐阅读