如何在一个元素上渲染多个阴影?

7
例如,如何完成:
box-shadow: 2px 2px 4px rgba(0, 0, 0, .05), -2px -2px 4px rgba(0, 0, 0, .05);

在React Native中,样式表是用来定义组件样式的。

我认为你不能那样做。我想到了BoxShadow,但我不认为它存在/有效。 - Chris
2个回答

4

我认为你不能这样做,但是为了另一层阴影而将组件包裹在另一个组件中的黑客技巧也是本世纪最糟糕的黑客技巧之一:

<div style={{ boxShadow: "2px 2px 4px rgba(0, 0, 0, .05)"}}>
  <div style={{ boxShadow: "-2px -2px 4px rgba(0, 0, 0, .05)"}}>
  { content }
  </div>
</div>

这是用于网络的吗? - Juan Je García
1
你是指“不是”吗? - SpoonMeiser

1
我创建了一个 React 组件,可以自动为每个需要的阴影创建多个 View 组件。它可能有一些小问题,但在我的情况下运行良好。
import React from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';
import * as _ from 'lodash';

const partitionByKeys = (keys, obj) => {
  let pass = {};
  let fail = {};

  for (const key of Object.keys(obj)) {
    if (keys.includes(key)) {
      pass[key] = obj[key];
    } else {
      fail[key] = obj[key];
    }
  }

  return [pass, fail];
};

const innerStyleKeys = [
  'padding', 'paddingTop', 'paddingBottom', 'paddingLeft', 'paddingRight',
  'paddingHorizontal', 'paddingVertical',
  'backgroundColor', 'flexDirection', 'justifyContent', 'alignItems',
  'minHeight', 'minHeight',
];

const ShadowView = ({ level = 0, shadows, children, style, ...props }) => {
  const shadow = _.head(shadows);
  const [innerStyle, outerStyle] = style ? partitionByKeys(innerStyleKeys, style) : [{}, {}];

  return (
    <View
      {...props}
      style={{
        shadowColor: shadow.color,
        shadowOffset: shadow.offset,
        shadowOpacity: shadow.opacity,
        shadowRadius: shadow.radius,
        ...(level === 0 ? outerStyle : {}),
        ...(shadows.length === 1 ? innerStyle : {}),
      }}
    >
      { shadows.length === 1 ?
        children :
        <ShadowView level={level + 1} shadows={_.tail(shadows)} style={style}>{children}</ShadowView>
      }
    </View>
  );
};

export default ShadowView;

使用方法:

<ShadowView shadows={[{  color: '#FF0000',  opacity: 0.5,  offset: {    width: 0,    height: 10,  },  radius: 60,}, {  color: '#00FF00',  opacity: 0.5,  offset: {    width: 0,    height: 3,  },  radius: 20,}]}>...</ShadowView>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接