简体   繁体   English

在React Native中全局加载文件

[英]Load files globally in react native

i am new to react native. 我是新来的本地人。 I was wondering is there anyway to load CSS,Colors globally to all components and screens rather then importing in each screen. 我想知道是否可以将CSS,Colors全局加载到所有组件和屏幕,而不是在每个屏幕中导入。

I have one reusable stylesheet.js and colors.js which contain all global css and colors. 我有一个可重用的stylesheet.js和colors.js,其中包含所有全局CSS和颜色。 stylesheet.js stylesheet.js

'use strict';

import {StyleSheet} from 'react-native';
import colors from './colors';


module.exports = StyleSheet.create({

    container:{
        flex:1,
    },

    alwaysred: {
       color:colors.txt_main,
    },

});

But now to use in components i need to import in every component. 但是现在要在组件中使用,我需要在每个组件中导入。 So i was wondering if there is more easy way to import the stylesheet and colors to all scrrens/components. 所以我想知道是否有更简单的方法来将样式表和颜色导入所有屏幕/组件。

I tried to importing in index.js ,but then when i tried to access style property it saying style undefined Something like this 我试图导入index.js,但是当我尝试访问style属性时,它说style undefined像这样

Index.js Index.js

import { AppRegistry } from 'react-native';
import stylesheet from './app/resources/styles/stylesheet';

import App from './app/App';

AppRegistry.registerComponent('newApp', () => App);

App.js App.js

 <Text style={stylesheet.alwaysred}>
     New stylesheet imported globally
  </Text>

This giving error saying undefined stylesheet. 这给了错误,说未定义的样式表。 I have folloed this Stackoverflow thread link to create global stylesheet 我已经关注了这个Stackoverflow线程链接以创建全局样式表

Use global : 使用global

global.stylesheet = StyleSheet.create({

    container:{
        flex:1,
    },

    alwaysred: {
       color:colors.txt_main,
    },

});

The canonical React way of achieving this is creating your own styled, components. 实现这一目标的标准React方法是创建自己的样式化组件。 For example, if you wanted all the Text elements in your application to be red, you can define your own component for it: 例如,如果您希望应用程序中的所有Text元素均为红色,则可以为其定义自己的组件:

// Text.js
import { Text, StyleSheet } from 'react-native';

const StyledText = ({ style, ...props }) => (
  <Text style={[styles.text, style]} {...props}></Text>
)

const styles = StyleSheet.create({
  text: {
    color: 'red'
  }
});

export default StyledText;

And then you can use that text component where you'd normally use Text from react-native: 然后,您可以在通常使用react-native的Text地方使用该text组件:

import Text from 'Text';

This is a little verbose, so often people use libraries like glamorous-native or styled-components to achieve the same effect. 这有点冗长,因此人们经常使用类似glamour-nativestyled-components的库来达到相同的效果。

// glamorous
const MyStyledText = glamorous.text({
  color: 'red'
});

// styled-components
const MyStyledText = styled.Text`
  color: red;
`;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM