Material-UI 中依赖道具的切换颜色
props-dependent Switch color in Material-UI
以下代码改编自 Material-UI 文档 customizing Switch
允许将开关颜色设置为蓝色:
import React from 'react'
import Switch from '@material-ui/core/Switch'
import {withStyles} from '@material-ui/core/styles'
const ColoredSwitch = withStyles({
switchBase: {
'&$checked': {
color: 'blue',
},
},
checked: {},
track: {},
})(Switch)
但是当尝试调整它以便可以通过组件属性设置颜色时,它就是行不通。以下代码(仅是伪动态的)事件呈现为默认开关:
const ColoredSwitch = withStyles({
switchBase: {
'&$checked': {
color: props => 'blue',
},
},
checked: {},
track: {},
})(Switch)
我想我一定是做错了什么,但不知道是什么。
如果必须使用 withStyles
HOC,请按照此示例传递道具:https://material-ui.com/styles/basics/#adapting-the-higher-order-component-api
const ColoredSwitch = withStyles({
switchBase: {
"&.Mui-checked": {
color: (props) => props.customchecked
}
},
checked: {},
track: {}
})((props) => {
const { classes, ...other } = props;
return <Switch classes={{ switchBase: classes.switchBase }} {...other} />;
});
您也可以使用makeStyles
const useStyles = makeStyles({
switchBaseChecked: {
"&.Mui-checked": {
color: (props) => props.color
}
}
});
export default function Switches() {
const props = { color: "green" };
const classes = useStyles(props);
return (
<Switch
color="primary"
classes={{
checked: classes.switchBaseChecked
}}
/>
);
}
以下代码改编自 Material-UI 文档 customizing Switch
允许将开关颜色设置为蓝色:
import React from 'react'
import Switch from '@material-ui/core/Switch'
import {withStyles} from '@material-ui/core/styles'
const ColoredSwitch = withStyles({
switchBase: {
'&$checked': {
color: 'blue',
},
},
checked: {},
track: {},
})(Switch)
但是当尝试调整它以便可以通过组件属性设置颜色时,它就是行不通。以下代码(仅是伪动态的)事件呈现为默认开关:
const ColoredSwitch = withStyles({
switchBase: {
'&$checked': {
color: props => 'blue',
},
},
checked: {},
track: {},
})(Switch)
我想我一定是做错了什么,但不知道是什么。
如果必须使用 withStyles
HOC,请按照此示例传递道具:https://material-ui.com/styles/basics/#adapting-the-higher-order-component-api
const ColoredSwitch = withStyles({
switchBase: {
"&.Mui-checked": {
color: (props) => props.customchecked
}
},
checked: {},
track: {}
})((props) => {
const { classes, ...other } = props;
return <Switch classes={{ switchBase: classes.switchBase }} {...other} />;
});
您也可以使用makeStyles
const useStyles = makeStyles({
switchBaseChecked: {
"&.Mui-checked": {
color: (props) => props.color
}
}
});
export default function Switches() {
const props = { color: "green" };
const classes = useStyles(props);
return (
<Switch
color="primary"
classes={{
checked: classes.switchBaseChecked
}}
/>
);
}