是否有可能将var styles = StyleSheet.create从React.component分离到反应原生的不同脚本?

pho*_*ong 5 javascript reactjs react-native

是否有可能将var styles = StyleSheet.create从React.component分离到反应原生的不同脚本?

bor*_*mes 17

这是可能的.只需使用此模式创建一个js文件:

'use strict';

var React = require('react-native');

var myStyles = React.StyleSheet.create({
   style1: { },
   style2: { }
)}

module.exports = myStyles;
Run Code Online (Sandbox Code Playgroud)

然后在你的组件js中使用require来使用该样式表,例如假设你的样式js文件名为phongyewtong.js

var s = require('../the/path/to/phongyewtong');
Run Code Online (Sandbox Code Playgroud)

用法:

<View style = {s.style1} />
Run Code Online (Sandbox Code Playgroud)


Mah*_*esh 6

以下两个链接都很好地解释了如何将样式移出“结构”代码:

  1. https://hackernoon.com/manage-react-native-project-folder-structure-and-simplify-the-code-c98da77ef792
  2. https://medium.com/the-react-native-log/tips-for-styling-your-react-native-apps-3f61608655eb

基本上(从上面的链接#2 复制代码片段)将您的样式放在单独的 JS 中,比如 text.js 文件:

const text = StyleSheet.create({
    p: {
      color: 'black',
      fontFamily: 'Open Sans',
      fontSize: 14,
    },
    title: {
      fontWeight: 'bold',
      color: 'black',
      fontFamily: 'Open Sans',
      fontSize: 20,
    }
  });

export default text;
Run Code Online (Sandbox Code Playgroud)

在 React 组件中,你可以简单地导入这个文本样式,并直接使用它

<Text style={text.p}>settings</Text>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。