Javascript React和Material UI,是否有一种干净的方式来分解我发送给useStyles的道具
从材料文档中,这是我们向useStyles发送道具的方式Javascript React和Material UI,是否有一种干净的方式来分解我发送给useStyles的道具,javascript,reactjs,ecmascript-6,material-ui,Javascript,Reactjs,Ecmascript 6,Material Ui,从材料文档中,这是我们向useStyles发送道具的方式 const useStyles = makeStyles({ // style rule foo: props => ({ backgroundColor: props.backgroundColor, }), bar: { // CSS property color: props => props.color, }, }); function MyComponent() { /
const useStyles = makeStyles({
// style rule
foo: props => ({
backgroundColor: props.backgroundColor,
}),
bar: {
// CSS property
color: props => props.color,
},
});
function MyComponent() {
// Simulated props for the purpose of the example
const props = { backgroundColor: 'black', color: 'white' };
// Pass the props as the first argument of useStyles()
const classes = useStyles(props);
return <div className={`${classes.foo} ${classes.bar}`} />
}
const{isNavOpen}=props;
此处重复您可以创建一个函数,可以这样使用,以避免重复
const styleDrawerWidth = ( isNavOpen) => {
return isNavOpen ? drawerWidth : drawerWidthClosed
}
export const useStyles = makeStyles(
theme => ({
drawer(props) {
const {isNavOpen} = props;
return {
width: styleDrawerWidth(isNavOpen),
};
},
drawerPaper(props) {
const {isNavOpen} = props;
return {
width: styleDrawerWidth(isNavOpen),
};
},
我建议使用
props.isNavOpen
,就像文档中建议的那样,而不是进行解构。谢谢你,Avinash指导我找到答案!我所说的重复就是重复const{isNavOpen}=props代码>,看起来你没有处理好。然而,根据您的指导,答案是让您的函数如下所示const styleDrawerWidth=(props)=>{const{isNavOpen,drawerWidth,drawerWidthClosed}=props;return isNavOpen?drawerWidth:drawerWidthClosed}
const styleDrawerWidth = ( isNavOpen) => {
return isNavOpen ? drawerWidth : drawerWidthClosed
}
export const useStyles = makeStyles(
theme => ({
drawer(props) {
const {isNavOpen} = props;
return {
width: styleDrawerWidth(isNavOpen),
};
},
drawerPaper(props) {
const {isNavOpen} = props;
return {
width: styleDrawerWidth(isNavOpen),
};
},