简体   繁体   English

在反应中将样式从父组件传递给 mui 组件

[英]Passing styles from parent to mui component in react

Hi I have the following React component that positions its children with styles.嗨,我有以下 React 组件,它使用样式定位其子项。

const styles = () => ({  
    bathButt : {
        top :278,
        left : 336
    },        
})
class AudioZones extends Component {

    render() {
        const { classes } = this.props;
        return ( 
                <IconButton  className={classes.bathButt} >
                    <Speaker/> 
                </IconButton>
                );
             } 
        }
export default withStyles(styles) (AudioZones);

I have created a child component "AudioZone" render() return ( );我创建了一个子组件“AudioZone” render() return ( ); } which i substitute into the parent我将其替换为父级

render() {
        const { classes } = this.props;
        return ( 
                <AudioZone/>                    );
             } 

However I have run into trouble on how I pass down the "bathButt" style so that the position of the button is set in the parent but read and rendered by the child.但是,我在如何传递“bathButt”样式以便按钮的位置在父级中设置但由子级读取和呈现时遇到了麻烦。

Any help appreciated任何帮助表示赞赏

For withStyles you can use Higher-Order Components (HOC) to pass styles from parent to child对于withStyles您可以使用高阶组件 (HOC) 将样式从父级传递到子级

const styles = () => ({
  bathButt: {
    top: 20,
    left: 30,
    backgroundColor: "blue"
  }
});


const withMyStyles = WrappedComponent => {
  const WithStyles = ({ classes }) => {
    return (
      <div>
        <WrappedComponent classes={classes} />
      </div>
    );
  };

  return withStyles(styles)(WithStyles);
};

and use it in your child component并在您的子组件中使用它

class AudioZones extends Component {
  render() {
    const { classes } = this.props;
    return (
      <IconButton className={classes.bathButt}>
        <h1>Speaker Component</h1>
      </IconButton>
    );
  }
}
export default withMyStyles(AudioZones);

but insted of withStyles you can use makeStyles ,i think its easer但是安装了withStyles你可以使用makeStyles ,我认为它更容易

const useStyles = makeStyles({
  bathButt: { top: 20, left: 50, color: "red" } // a style rule
});


function App(props) {
  return <AudioZones useStyles={useStyles} />;
}

child component子组件

function AudioZones(props) {
  const classes = useStyles();
  return (
    <div>
      <IconButton className={classes.bathButt}>
        <h1>Speaker Component</h1>
      </IconButton>
    </div>
  );
}

Working Codesandbox for withStyles and makeStyles withStylesmakeStyles 的工作代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM