代码之家  ›  专栏  ›  技术社区  ›  Buggy

如何在react中重用react原生样式表?

  •  1
  • Buggy  · 技术社区  · 6 年前
    // 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>
    

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

    在这两种情况下,react native和react?

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

    问题 as is 没有魔术师。

    2 回复  |  直到 6 年前
        1
  •  2
  •   jman93    6 年前

    你能做的就是把你所有的样式都存储在某个文件中的一个对象中 e.g. const containerStyles = { borderRadius: 2 }

    import {containerStyles} from '../someFile.js'
    
    const styles = StyleSheets.create({
      container: containerStyles
    })

    emotion.js 在JS中动态加载CSS

    https://github.com/emotion-js/emotion

    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>
        )
      }
    }

    我希望这有帮助

        2
  •  0
  •   Mathias Silva    6 年前

    您可以将新组件的样式与容器的样式连接起来,如下所示

    const styles = StyleSheet.create({
      container: {
        borderRadius: 4,
        borderWidth: 0.5,
        borderColor: '#d6d7da',
      },
      newComponent:{
         // New component style
      }
    });
    
    <View style={[styles.container, styles.newComponent]}> 
    </View>
    
        3
  •  0
  •   ABHIJEET KHIRE    5 年前
    // your component file name  (button.js) 
    import React, { Component } from 'react';
    
    // import the style from another file present in the same directory
    import styles from 'button.style.js'; 
     // you can reuse this style in another component also
    
    class Button extends Component {
        render() {
            return (
                <View style={styles.container}>
                    <Text style={styles.buttonText}> Press Me! </Text>
                </View>
            );
        }
    }
    
    export default Button;
    
    // your style file  name ( "button.style.js")
    
    import { StyleSheet } from 'react-native';
    
    export default StyleSheet.create({
        container: {
            padding: 10,
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: '#43a1c9',
        },
        buttonText: {
            fontSize: 20,
            textAlign: 'center'
        }
    });