如何在反应中重用反应原生样式表(样式)? [英] How to reuse react-native StyleSheet (styles) in react?

查看:33
本文介绍了如何在反应中重用反应原生样式表(样式)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//react-native 示例import { StyleSheet, View } from 'react-native';常量样式 = {容器: {边界半径:4,边框宽度:0.5,边框颜色:'#d6d7da',}}const styleRN = StyleSheet.create(styles);<视图样式={stylesRN.container}></View>

什么是重用的最佳方式

//内部样式{边界半径:4,边框宽度:0.5,边框颜色:'#d6d7da',}

在 react-native 和 react 中?

我想用伪代码(或 React 中的另一种重用方式)实现的目标:

<div style={magicAdapter(styles.container)}>Hello World!</div>

问题:如果没有magicAdapter,不可能在react as is 中重用所有react-native inline-styles.

解决方案

您可以做的是将所有样式存储在某个文件中的对象中 e.g.const containerStyles = { borderRadius: 2 },将其导出,然后对于 React Native,使用 StyleSheets javascript 类为您的 div 容器创建样式

从 '../someFile.js' 导入 {containerStyles}const 样式 = StyleSheets.create({容器:containerStyles})

然后对于 React,您可以使用相同的对象进行内联样式,但请注意,并非 StyleSheets 中支持的所有样式都可以用于内联样式,因此如果您想做一些等效的事情,则可以使用诸如 emotion 之类的库.js 在 JS 中动态加载 CSS

https://github.com/emotion-js/emotion举个例子

从'emotion'导入{css}从 '../someFile' 导入 {containerStyle}const getContainerStyles = css`边界半径:${containerStyle.borderRadius}`导出默认类 SomeClass 扩展组件 {使成为() {返回(

)}}

希望能帮到你

// react-native example
import { StyleSheet, View } from 'react-native';

const styles = {
  container: {
    borderRadius: 4,
    borderWidth: 0.5,
    borderColor: '#d6d7da',
  }
}

const stylesRN = StyleSheet.create(styles);

<View style={stylesRN.container}></View>

What the best way to reuse

// inner styles 
{
    borderRadius: 4,
    borderWidth: 0.5,
    borderColor: '#d6d7da',
}

in both react-native and react?

What i want to achieve in pseudocode (or another way of reuse in React):

<div style={magicAdapter(styles.container)}>Hello World!</div>

Problem: It is impossible to reuse all react-native inline-styles in react as is without magicAdapter.

解决方案

What you could do is store all your styles in an object in some file e.g. const containerStyles = { borderRadius: 2 }, export it, then for React Native use the StyleSheets javascript class to create the styles for your div container

import {containerStyles} from '../someFile.js'

const styles = StyleSheets.create({
  container: containerStyles
})

then for React you could do inline styling with the same object, but be aware that not all styles supported in StyleSheets can be used for inline styling, so if you want to do something equivalent there's libraries out there like emotion.js to dynamically load CSS in JS

https://github.com/emotion-js/emotion Heres an example

import {css} from 'emotion'
import {containerStyle} from '../someFile'

const getContainerStyles = css`
  border-radius: ${containerStyle.borderRadius}
`

export default class SomeClass extends Component {
  render() {
    return(
      <div
        style={getContainerStyles}
      >
      </div>
    )
  }
}

I hope this helps

这篇关于如何在反应中重用反应原生样式表(样式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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