如何解决不使用 React-jss 渲染的动态创建的样式
我在我的 React 项目中使用 react-jss
。
我想根据通过 createUseStyles
例如:
在组件中
const useStyles = createUseStyles (styleProp)
在样式表中
type1 = () => {
return {
className : {
backgroundColor : 'blue',}
}
}
type2 = () => {
return {
className : {
backgroundColor : 'green',}
}
}
switch (styleProp) {
case 'type1' :
return type1 ();
case 'type2' :
return type2 ();
}
我第一次用特定的 styleProp
调用它时效果很好。它呈现正确的 bg 颜色。但是当下次类型改变时,通过正确的类型函数但是渲染的样式不正确。
如果有人能告诉我我做错了什么,那就太好了!
解决方法
从官方文档来看,你需要做类似这样的事情:
import React from 'react'
import {createUseStyles} from 'react-jss'
const useStyles = createUseStyles({
myButton: {
padding: props => props.spacing
},myLabel: props => ({
display: 'block',color: props.labelColor,fontWeight: props.fontWeight,fontStyle: props.fontStyle
})
})
const Button = ({children,...props}) => {
const classes = useStyles(props)
return (
<button className={classes.myButton}>
<span className={classes.myLabel}>{children}</span>
</button>
)
}
Button.defaultProps = {
spacing: 10,fontWeight: 'bold',labelColor: 'red'
}
const App = () => <Button fontStyle="italic">Submit</Button>
现在如果你想动态更新它,你可以维护一个状态,并将变量值存储在那个状态,你可以使用 setState 函数更新状态,这肯定会用正确的预期输出更新你的 UI。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。