从组件的“样式"中获取 CSS 属性值支柱 [英] Get CSS property values from a component's "style" prop

查看:55
本文介绍了从组件的“样式"中获取 CSS 属性值支柱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个库编写 React Native 组件,我希望用户能够使用 style 属性对其进行样式设置,就像 React.View 和其他内置组件.

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.

为此,我需要能够从传递的任何内容中提取实际的 CSS 属性(例如 borderWidth: 2backgroundColor: 'pink')style 道具.只要它是一个普通对象就可以了,但它也可能是调用 React.StyleSheet.create.这似乎是一个不透明的对象,所有选择器都简单地映射到数字 ID.

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.

如何解决这些问题并获得实际的 CSS 属性,以便对它们做任何比直接将它们直接传递给 View 更复杂的事情?

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?

推荐答案

内置 StyleSheet.flatten 函数(或相同的 flattenStyle 函数)可以将任何可以合法传递给 style 道具的对象转换为映射 CSS 属性名称的对象值.它适用于普通对象、StyleSheet.create() 返回的 ID 和数组.

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.

从组件定义中检查 style 属性中指定的宽度的示例用法:

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;

这篇关于从组件的“样式"中获取 CSS 属性值支柱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆