如何在 React Native 中导入和导出样式?

Aja*_*ran 4 css styles react-native

我是原生反应新手。我了解了组件的好处,嵌入外部样式。现在我尝试使用全局样式。我想在整个应用程序中使用相同样式的文本、按钮。

最好不要在每个组件中重复样式,我想在 styles 包下创建单独的 text.js、button.js 来自定义视图样式。 在此输入图像描述

这是我的项目结构。我想将 text.js 导入到我的 index.js 中。

索引.js

import { AppRegistry } from 'react-native';
import React, {Component} from 'react';
import {
  Text
} from 'react-native';
import text from './App/styles';

export default class FirstApp extends Component{
    render(){
      return (
        <Text styles={text.p}>Customising React</Text>
      );
    }
}
AppRegistry.registerComponent('FirstApp', () => FirstApp);
Run Code Online (Sandbox Code Playgroud)

文本.js

import{
  StyleSheet
} from 'react-native';

export default const text = StyleSheet.create({
  p: {
    color: 'blue',
    fontSize: 14
  }
});
Run Code Online (Sandbox Code Playgroud)

有没有办法将我的 text.js 样式导入到 index.js 中的文本视图中?

ric*_*ysy 7

创建一个名为“style.js”的新文件

export const customStyle = StyleSheet.create({
   blueblue:{
      color: blue
   }
})
Run Code Online (Sandbox Code Playgroud)

并在你的组件文件中

import {customStyle} from './style'

...
<Text style={customStyle.blueblue}>Hi</Text>
Run Code Online (Sandbox Code Playgroud)


lue*_*emj 5

导出默认常量无效。 如果您希望文本成为默认导出,则需要定义它并在单独的语句中导出。

const text = StyleSheet.create({...}); export default test;

此外,您的导入路径似乎与您的实际应用程序结构不匹配。

从“./App/styles”导入文本;

改成

从“./styles/text.js”导入文本;