简体   繁体   中英

Passing props to makeStyles react

I have this component

 const MyComponent = (props) => {
  const classes = useStyles(props);

  return (
    <div
      className={classes.divBackground}
      backgroundImageLink={props.product?.image}
      sx={{ position: "relative" }}
    ></div>
  );
};


export default MyComponent;

I am trying to pass backgroundImage link in props and trying to put into makeStyles

export default makeStyles(props => ({
    divBackground:{
        background:`url("${props.backgroundImageLink}")`,
    }
}));

But this does not works

& I am getting this warning in console

index.js:1 Warning: React does not recognize the `backgroundImage` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `backgroundimage` instead. If you accidentally passed it from a parent component, remove it from the DOM element.

You're not supposed to pass arbitrary attributes to the native elements ( div in this case) because it doesn't do anything. The prop only works when passed in useStyles :

export default makeStyles(props => ({
    divBackground:{
        background:`url("${props.product?.image}")`,
    }
}));

Usage

 const MyComponent = (props) => {
  // you only need to pass the props here. useStyles will then use the
  // prop.product.image to create the background property, generate a
  // stylesheet and return the class name for you.
  const classes = useStyles(props);

  return (
    <div
      className={classes.divBackground}
      // remove this line -----> backgroundImageLink={props.product?.image}
      sx={{ position: "relative" }}
    ></div>
  );
};
    const MyComponent = (props) => {
  const classes = useStyles(props)();

  return (
    <div
      className={classes.divBackground}
      backgroundImageLink={props.product?.image}
      sx={{ position: "relative" }}
    ></div>
  );
};


export default MyComponent;

then :

export default useStyles=(props)=>makeStyles(()=> ({
    divBackground:{
        background:`url("${props.backgroundImageLink}")`,
    }
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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