我可以在React Native中制作动态样式吗?

Pet*_*rne 110 css reactjs react-native

假设我有一个像这样的渲染组件:

<View style={jewelStyle}></View>
Run Code Online (Sandbox Code Playgroud)

jewelStyle =

  {
    borderRadius: 10,
    backgroundColor: '#FFEFCC',
    width: 20,
    height: 20,
  },
Run Code Online (Sandbox Code Playgroud)

如何使背景颜色动态并随机分配?我试过了

  {
    borderRadius: 10,
    backgroundColor: getRandomColor(),
    width: 20,
    height: 20,
  },
Run Code Online (Sandbox Code Playgroud)

但这使得View的所有实例都具有相同的颜色,我希望每个实例都是唯一的.

有小费吗?

Jim*_*erg 156

我通常做的事情是这样的:

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

...

jewelStyle = function(options) {
   return {
     borderRadius: 12,
     background: randomColor(),
   }
 }
Run Code Online (Sandbox Code Playgroud)

每次渲染View时,都会使用与之关联的随机颜色实例化新的样式对象.当然,这意味着每次重新渲染组件时颜色都会改变,这可能不是您想要的.相反,你可以做这样的事情:

var myColor = randomColor()
<View style={jewelStyle(myColor)} />
Run Code Online (Sandbox Code Playgroud)

...

jewelStyle = function(myColor) {
   return {
     borderRadius: 10,
     background: myColor,
   }
 }
Run Code Online (Sandbox Code Playgroud)

  • @DominicTobias Stylesheet.create打包并将样式"发送"到本机区域一次.这意味着,当您多次重复使用相同的样式,或多次加载相同的组件时,它将重用该样式而不是打包并再次"发送".例如,如果您正在加载3000个样式的行,那么您将感受到相当大的性能提升. (25认同)
  • 此方法根本不使用样式表.那些使用`Stylesheet.create()`声明Stylesheets的目的是什么? (21认同)
  • 使用Stylesheet.create有很多好处吗? (4认同)
  • @fatuhoku当你需要在多个地方重复使用相同的风格时,这很好 (2认同)

小智 55

是的,你可以,实际上,你应该StyleSheet.create用来创建你的风格.

import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View
} from 'react-native';    

class Header extends Component {
    constructor(props){
        super(props);
    }    

    render() {
        const { title, style } = this.props;
        const { header, text } = defaultStyle;
        const combineStyles = StyleSheet.flatten([header, style]);    

        return (
            <View style={ combineStyles }>
                <Text style={ text }>
                    { title }
                </Text>
            </View>
        );
    }
}    

const defaultStyle = StyleSheet.create({
    header: {
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#fff',
        height: 60,
        paddingTop: 15,
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 3 },
        shadowOpacity: 0.4,
        elevation: 2,
        position: 'relative'
    },
    text: {
        color: '#0d4220',
        fontSize: 16
    }
});    

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

然后:

<Header title="HOME" style={ {backgroundColor: '#10f1f0'} } />
Run Code Online (Sandbox Code Playgroud)

  • 这个答案显示了样式表中定义样式的一个很好的示例,但稍后可以在组件中重写 (7认同)
  • 如文档中所述,使用`StyleSheet.flatten`的AFAIK只会丢弃`StyleSheet.create`中的任何优化:直接引用样式对象将使您失去这些优化。” (https://facebook.github.io/react-native/docs/stylesheet.html)。 (2认同)

小智 23

如果您仍想利用StyleSheet.create并拥有动态样式,请尝试以下方法:

const Circle = ({initial}) => {


const initial = user.pending ? user.email[0] : user.firstName[0];

    const colorStyles = {
        backgroundColor: randomColor()
    };

    return (
        <View style={[styles.circle, colorStyles]}>
            <Text style={styles.text}>{initial.toUpperCase()}</Text>
        </View>
    );
};

const styles = StyleSheet.create({
    circle: {
        height: 40,
        width: 40,
        borderRadius: 30,
        overflow: 'hidden'
    },
    text: {
        fontSize: 12,
        lineHeight: 40,
        color: '#fff',
        textAlign: 'center'
    }
});
Run Code Online (Sandbox Code Playgroud)

注意如何将style属性View设置为一个将样式表与动态样式组合在一起的数组.


Yog*_*are 7

在语法上有一些问题.这对我有用

<Text style={StyleSheet.flatten([styles.textStyle,{color: 'red'}])}> Hello </Text>

const styles = StyleSheet.create({
   textStyle :{
      textAlign: 'center',   
      fontFamily: 'Arial',
      fontSize: 16
  }
  });
Run Code Online (Sandbox Code Playgroud)


s̮̦*_*̥̳̼ 6

最简单的是我的:

<TextInput
  style={[
    styles.default,
    this.props.singleSourceOfTruth ?
    { backgroundColor: 'black' } 
    : { backgroundColor: 'white' }
]}/>
Run Code Online (Sandbox Code Playgroud)


Sha*_*ant 6

  import React, { useContext, useMemo } from 'react';
  import { Text, StyleSheet, View } from 'react-native';
  import colors from '../utils/colors';
  import ThemeContext from './../contexts/ThemeContext';

  export default (props) => {
    const { theme } = useContext(ThemeContext);

    // Constructing styles for current theme
    const styles = useMemo(() => createStyles(theme), [theme]);

    return (
      <View style={styles.container}>
        <Text style={styles.label}>{label}</Text>
      </View>
    );
  };

  const createStyles = (theme: AppTheme) =>
    StyleSheet.create({
      container: { width: '100%', position: 'relative', backgroundColor: colors[theme].background },
      label: {
        fontSize: 13,
        fontWeight: 'bold',
      },
    });
Run Code Online (Sandbox Code Playgroud)

颜色.ts

export type AppTheme = 'dark' | 'light';

const light: Colors = {
  background: '#FFFFFF',
  onBackground: '#333333',
  gray: '#999999',
  grayLight: '#DDDDDD',
  red: 'red',
};

const dark: Colors = {
  background: '#333333',
  onBackground: '#EEEEEE',
  gray: '#999999',
  grayLight: '#DDDDDD',
  red: 'red',
};

const colors = {
  dark,
  light,
  primary: '#2E9767',
  secondary: '#F6D130',
};

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


Col*_*say 5

你会想要这样的东西:

var RandomBgApp = React.createClass({
    render: function() {

        var getRandomColor = function() {
            var letters = '0123456789ABCDEF'.split('');
            var color = '#';
            for (var i = 0; i < 6; i++ ) {
                color += letters[Math.floor(Math.random() * 16)];
            }
            return color;
        };

        var rows = [
            { name: 'row 1'},
            { name: 'row 2'},
            { name: 'row 3'}
        ];

        var rowNodes = rows.map(function(row) {
            return <Text style={{backgroundColor:getRandomColor()}}>{row.name}</Text>
        });

        return (
            <View>
                {rowNodes}
            </View>
        );

    }
});
Run Code Online (Sandbox Code Playgroud)

在此示例中,我采用包含组件中行数据的行数组,并将其映射到一个 Text 组件数组。getRandomColor每次创建新的 Text 组件时,我都会使用内联样式来调用该函数。

您的代码的问题在于您定义了一次样式,因此 getRandomColor 只被调用一次 - 当您定义样式时。