【问题标题】:react-material-ui withStyle props is emptyreact-material-ui withStyle 道具为空
【发布时间】:2021-05-28 01:32:08
【问题描述】:

我想控制切换到道具的背景颜色。但是 withStyles 的 props 是空的。

import Switch from '@material-ui/core/Switch';
import {withStyles, Theme, createStyles} from '@material-ui/core/styles';
import React from 'react';
import {PropsType} from "./propsType";

const AntSwitch = withStyles(({palette, props, ...other})=>{
    console.log('withStyles', props) // here is empty
    return ({
        switchBase: {
            '&$checked': {
                '& + $track': {
                    opacity: 1,
                    backgroundColor: (props as PropsType.Switch).activeColor ?? palette.primary.main,
                    borderColor: palette.primary.main,
                },
            },
        }
    })
})(Switch);

export default function TPSwitch(props: PropsType.Switch) {
    const {label, ...other} = props;
    console.log('other', props)
    return (
        <AntSwitch {...other} />
    )
};

在控制台中打印

other {label: "on", activeColor: "#E74060"}
TPSwitch.tsx:8 withStyles {}

【问题讨论】:

    标签: reactjs typescript material-ui


    【解决方案1】:

    withStyles 不将props 视为its arguments 之一

    这是您可以访问props 的方式。为了清楚起见,我简化了您的示例。

    const AntSwitch = withStyles(({ palette }) => ({
      root: {
        backgroundColor: (props) => console.log(palette, props) || "hotpink"
      }
    }))(Switch);
    

    【讨论】:

    • 非常感谢您的建议!代码对我有用。但并不完美。 props lambda 在元素属性中起作用,但不适用于事件。例如,'&amp;$checked' : (props) =&gt;({ color : props.customColor}) 谢谢。
    • 不完全确定我理解这个问题。 reference a local rule 有帮助吗?
    • codesandbox.io/s/react-jss-dynamic-global-value-j552b 这是同样的问题。这个问题不仅仅是关于名称的虚假陈述。我想这是很多人都会遇到的问题。感谢您的时间。我会发现更多,所以如果你有任何想法,请告诉我。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    • 2018-11-14
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    相关资源
    最近更新 更多