【问题标题】:react-jss dynamic value not working in queryreact-jss 动态值在查询中不起作用
【发布时间】:2021-08-16 11:50:57
【问题描述】:

我试图通过 react-jss 使用 props 来控制样式值

https://cssinjs.org/react-jss/?v=v10.6.0

但是,动态值在查询中不起作用!

这段代码是用 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


【解决方案1】:

如果使用material-ui库,使用makeStyles函数创建useStyles钩子。

import React from "react";
import ReactDOM from "react-dom";
import { makeStyles } from '@material-ui/styles';

const styles = {
  "@global": {
    body: {
      backgroundColor: ({ color }) => color
    }
  }
};

const useStyles = makeStyles(styles);

let App = props => {
  useStyles(props);
  return <h1>Background should be yellow</h1>;
};

ReactDOM.render(<App color="yellow" />, document.getElementById("root"));

【讨论】:

  • 感谢您的建议。我认为动态值在查询中有错误,但是我看到了这一点并意识到我认为是错误的。还有更复杂的条件。我在这里安排了一个更详细的情况。 [codesandbox.io/s/…无论这个问题是否解决,我都感谢您的努力和时间。多亏了你,我才能知道更多。谢谢
猜你喜欢
  • 1970-01-01
  • 2017-07-08
  • 2020-08-11
  • 1970-01-01
  • 1970-01-01
  • 2018-09-01
  • 2017-12-14
  • 1970-01-01
  • 2019-07-16
相关资源
最近更新 更多