首页 文章

改变JSS中的风格

提问于
浏览
1

我有以下使用JSS的组件:

import React from 'react'
import injectSheet from 'react-jss'

const styles = {
  button: {
    backgroundColor: 'pink',
  }
}

class App extends Component {
    changeStyle = () => {
         styles.button.backgroundColor: 'blue' //this obviously doesn't work
    }
    render() {
        return (
            <div className="App">
                <button className={this.props.classes.button} onClick={this.changeStyle}>Switch user</button>
            </div>
        );
    }
}

这绝对是一个简单的问题 . 当我点击按钮时,我希望背景会变为“蓝色”,但只是指定新颜色不起作用 .

3 回答

  • 0

    理想的模式是将按钮的颜色存储在状态对象中,然后在要更改颜色时更新该状态 .

    您的问题的一个解决方案是这样的:

    import React from 'react'
    import injectSheet from 'react-jss'
    
    
    class App extends Component {
    
      constructor(props) {
        super(props);
        this.state = {buttonColor: 'pink'};
    
      }
        changeStyle = (color) => {
          this.setState({
            buttonColor: color
          });
        }
    
        render() {
            return (
                <div className="App">
                    <button className={this.props.classes.button} onClick={ this.changeStyle }>Switch user</button>
                </div>
            );
        }
    }
    
  • 1

    JSS中的条件样式

    在JSS中,您应该使用函数将样式名称(作为字符串)注入组件 . 我假设您正在使用injectSheet将类注入到道具中,并将其从代码示例中删除 . injectSheet将注入包含键值对的classes对象,如下所示:[styleObjectPropertyName]:[dynamicInjectedCSSPropertyName],它会将CSS注入页面的 Headers 中 .

    当您尝试在发生这种情况后编辑样式对象时,它不会被动,因此您需要事先准备好CSS样式并在代码中动态删除或应用它们 .

    classNames包

    您可以使用像classNames这样的简单库来有条件地应用样式,这是我在下面概述的方式 .

    import React from 'react';
    import injectSheet from 'react-jss';
    
    const styles = {
      buttonPink: {
        backgroundColor: 'pink',
      },
      buttonBlue: {
        backgroundColor: 'blue',
      },
    };
    
    class App extends Component {
      state = {
        isButtonColorPink: true,
      };
    
      changeButtonColor = () => {
    
      }
    
      render() {
        const { buttonColorPink } = this.state;
        const { classes } = this.props;
        return (
          <div className="App">
            <button className={classNames({ 
              [classes.buttonPink]: isButtonColorPink,
              [classes.buttonBlue]: !isButtonColorPink,
            })} onClick={this.toggleStyle}>Switch user</button>
          </div>
        );
      }
    }
    
    export default injectSheet(styles)(App);
    

    或者,您可以使用内联样式进行任何动态样式 - 如按钮内的 style={{ backgroundColor: this.state.buttonColor }} ,只需在类方法中使用thisState更改buttonColor属性 .

  • 1

    使用JSS版本7.1.7,您可以使用函数值来定义样式 .

    const styles = {
      button: {
        color: data => data.color
      }
    }
    

    当你需要改变颜色时,调用 sheet 道具的 update 方法:

    this.props.sheet.update({
      button: {
        color: 'red',
      }
    })
    

    请注意,截至2018年8月,有limitations使用函数值

相关问题