我有以下使用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>
);
}
}这绝对是一个简单的问题。当我点击按钮时,我希望背景会变成“蓝色”,但仅仅分配新的颜色是行不通的。
发布于 2018-04-30 01:01:36
JSS中的条件样式
在JSS中,应该使用一个函数将样式名称(作为字符串)注入到组件中。我假设您正在使用injectSheet将类注入到属性中,只是在您的代码示例中忽略了这一点。injectSheet将注入包含键值对的类对象,比如: styleObjectPropertyName: dynamicInjectedCSSPropertyName,它将把CSS注入页面的头部。
当您尝试在此之后编辑样式对象时,它不是被动的,因此您需要预先准备好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属性。
发布于 2018-04-30 01:01:03
理想的模式是将按钮的颜色存储在状态对象中,然后在您想要更改颜色时更新该状态。
你的问题的一个解决方案是这样的:
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>
);
}
}发布于 2018-08-30 02:43:53
使用JSS版本7.1.7+,您可以使用函数值来定义您的样式。
const styles = {
button: {
color: data => data.color
}
}当您需要更改颜色时,调用sheet prop的update方法:
this.props.sheet.update({
button: {
color: 'red',
}
})请注意,截至2018年8月,使用函数值的limitations
https://stackoverflow.com/questions/50089058
复制相似问题