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

时间:2016-05-03 07:24:59

标签: css reactjs react-native

例如,如何完成

box-shadow: 2px 2px 4px rgba(0, 0, 0, .05), -2px -2px 4px rgba(0, 0, 0, .05);

in react native styles?

3 个答案:

答案 0 :(得分:3)

我认为你不可以,但是用另一层阴影包裹你的组件只是为了另一层阴影的黑客攻击是本世纪最糟糕的黑客:

<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>

答案 1 :(得分:0)

我创建了一个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>

答案 2 :(得分:0)

您可以使用:

boxShadow:
'0px 2px 4px -1px rgba(0, 0, 0, 0.2), 0px 4px 5px 0px rgba(0, 0, 0, 0.14), 0px 1px 10px 0px rgba(0, 0, 0, 0.12)',