【问题标题】:How to pass variables to inline css function in React如何将变量传递给 React 中的内联 css 函数
【发布时间】:2019-07-23 08:43:07
【问题描述】:

我已经设法在 React 中创建了类,并希望将随机生成的背景设置为 div 容器。名为 divStyle 的常量变量确实包含 CSS 函数 rbg() 但我只是找不到将变量从 this.state 传递给该函数的解决方案

import React from 'react';
import './ShopItem.css';

class ShopItem extends React.Component{
constructor(props){
    super(props);
    this.state = {
        r:Math.floor(Math.random() * 256),
        g:Math.floor(Math.random() * 256),
        b:Math.floor(Math.random() * 256)        
    }
}

componentDidMount() {
    console.log(this.state.r, this.state.g, this.state.b);
} 

render(){

    const divStyle = {
        background: "rgb()"
    };

    return(
        <div className="Item" style={divStyle} >
            {console.log("test")}
            {this.props.data}
        </div>
    );
};
};

export default ShopItem;

【问题讨论】:

    标签: css reactjs react-router


    【解决方案1】:

    您可以使用 es6 反引号并添加使用以下代码,this 指的是当前实例,因此 this.state 在方法中可用。

    const divStyle = {
        background: `rgb(${this.state.r},${this.state.g},${this.state.b})`
    };
    

    【讨论】:

      【解决方案2】:

      您可以简单地将它们添加到字符串中:

      const divStyle = {
          background: "rgb(" + this.state.r + "," + this.state.g + "," + this.state.b + ")"
      };
      

      【讨论】:

        【解决方案3】:

        编写内联样式很快就会变得冗长、难以维护和丑陋。我会将 styled-components 视为您问题的解决方案。在我看来,这对于动态更改 React 组件的样式来说是一个更加灵活的解决方案

        这是链接 https://www.styled-components.com/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-01-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-20
          • 2011-06-21
          • 2020-07-24
          相关资源
          最近更新 更多