Get CSS property values from a component's “st

2020-07-02 11:29发布

问题:

I'm writing a React Native component for a library and I want users to be able to style it using the style property, just like React.View and other built-in components.

However, since my component is actually made up of a few nested views, I need to do some calculations to figure out what styling to put on the inner ones. For example, I might need to adjust the sizing of an image based upon the thickness of a border around it, or adjust a highlight color based upon the given text color, or in some other way infer some piece of styling from another piece of styling.

To do this, I need to be able to extract the actual CSS properties (like borderWidth: 2 or backgroundColor: 'pink') out of whatever gets passed as the style prop. This is fine as long as it comes as a plain object, but it may also be the result of a call to React.StyleSheet.create. This seems to be an opaque object with all selectors simply mapped to numeric IDs.

How can I resolve these and get the actual CSS properties, in order to do anything more complicated with them than simply passing them straight on to a View?

回答1:

The built-in StyleSheet.flatten function (or the identical flattenStyle function) can turn anything that can legitimately be passed to the style prop into an object mapping CSS property names to values. It works on plain objects, IDs returned by StyleSheet.create(), and arrays.

Example usage to check the width specified in the style prop from within a Component definition:

import { StyleSheet } from 'react-native'

// ... then, later, e.g. in a component's .render() method:

let width = StyleSheet.flatten(this.props.style).width;


回答2:

You need to import StylesheetRegistry:

StyleSheetRegistry = require("../../node_modules/react-native/Libraries/StyleSheet/StyleSheetRegistry"),

Then pass in the style ID:

var style = StyleSheetRegistry.getStyleByID(this.props.style)


回答3:

Please have a look on https://github.com/vitalets/react-native-extended-stylesheet#underscored-styles

Style created via extended stylesheet contains original values in underscored prop:

const styles = EStyleSheet.create({
  text: {
    fontSize: '1rem',
    color: 'gray'
  }
});

In runtime:

styles = {
  text: 0,
  _text: {
    fontSize: 16,
    color: 'gray'
  }
}