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

css CSS

Stafan小宇宙

2020-03-12

说我有一个带有这样的渲染的组件:

<View style={jewelStyle}></View>

其中jewelStyle =

  {
    borderRadius: 10,
    backgroundColor: '#FFEFCC',
    width: 20,
    height: 20,
  },

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

  {
    borderRadius: 10,
    backgroundColor: getRandomColor(),
    width: 20,
    height: 20,
  },

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

有小费吗?

第917篇《我可以在React Native中制作动态样式吗?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
伽罗理查德 2020.03.12

这是对我有用的东西:

render() {
  const { styleValue } = this.props;
  const dynamicStyleUpdatedFromProps = {
    height: styleValue,
    width: styleValue,
    borderRadius: styleValue,
  }

  return (
    <View style={{ ...styles.staticStyleCreatedFromStyleSheet, ...dynamicStyleUpdatedFromProps }} />
  );
}

For some reason, this was the only way that mine would update properly.

JinJinTom 2020.03.12

我知道有几个答案,但是我认为最好,最简单的方法是使用状态“更改”是该状态的目的。

export default class App extends Component {
    constructor(props) {
      super(props);
      this.state = {
          style: {
              backgroundColor: "white"
          }
      };
    }
    onPress = function() {
      this.setState({style: {backgroundColor: "red"}});
    }
    render() {
       return (
          ...
          <View style={this.state.style}></View>
          ...
       )
    }

}

LEY西门 2020.03.12

我通常按​​照以下方式进行操作:

<View style={this.jewelStyle()} />

...

jewelStyle = function(options) {
   return {
     borderRadius: 12,
     background: randomColor(),
   }
 }

Every time View is rendered, a new style object will be instantiated with a random color associated with it. Of course, this means that the colors will change every time the component is re-rendered, which is perhaps not what you want. Instead, you could do something like this:

var myColor = randomColor()
<View style={jewelStyle(myColor)} />

...

jewelStyle = function(myColor) {
   return {
     borderRadius: 10,
     background: myColor,
   }
 }

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android