【发布时间】:2021-08-16 11:50:57
【问题描述】:
我试图通过 react-jss 使用 props 来控制样式值
但是,动态值在查询中不起作用!
这段代码是用 react-jss 控制全局背景颜色。这段代码运行良好。但是,将背景颜色更改为在道具中使用动态值。不要改变背景颜色的值。
const styles = {
root: {
backgroundColor: ({ color }) => color
},
"@global": { // with query
body: {
backgroundColor: 'yellow' //working!!
}
}
};
此代码不起作用。我检查了({ color }) => color lambda 函数被调用并且值是正确的。
const styles = {
root: {
backgroundColor: ({ color }) => color
},
"@global": { // with query
body: {
backgroundColor: ({ color }) => color // not working
}
}
};
这是有错误的完整代码。
import React from "react";
import ReactDOM from "react-dom";
import { createUseStyles } from "react-jss";
const styles = {
root: { // with classKey
backgroundColor: ({ color }) => color // working
},
"@global": { // with query
body: {
backgroundColor: ({ globalColor }) => globalColor // not work
}
}
};
const useStyles = createUseStyles(styles);
const App = (props) => {
const classes = useStyles(props);
return <h1 className={classes.root}> Background should be yellow</h1>;
};
ReactDOM.render(<App color="yellow" globalColor='red'/>, document.getElementById("root"));
这里是codesandbox,这不是我的账号和密码
https://codesandbox.io/s/react-jss-dynamic-global-value-j552b
【问题讨论】:
-
我认为您必须评估工作表对象才能在组件安装后对其进行更新。有关如何解决此问题的示例,请参阅以下CodeSandbox
-
@OluwafemiSule 我用的是material-uil库,内部好像用的是jss sheet。因此,据我所知,没有办法获取工作表并对其进行更新。这个问题取自这里。 stackoverflow.com/questions/67731785/….
标签: javascript reactjs jss