简体   繁体   中英

Import styles css into a react js app

i have a trouble importing .css stylesheet on a react basic app, I have this components:

AvatarHeader.js:

import styles from './AvatarHeader.css';

export default function AvatarHeader({ style, children }) {
  return (
    <div>
      <img style={styles.image} src={Background} alt="background">
        { children }
      </img>

AvatarHeader.css:

.image {
   width: 400
}

AvatarHeader.js & AvatarHeader.css are in the same folder.

package.json:

  {
    "name": "UtWeb",
    "version": "0.1.0",
    "private": true,
    "devDependencies": {
      "css-loader": "^0.25.0",
      "react-scripts": "0.9.0",
      "webpack": "^2.2.1",
      "webpack-dev-server": "^1.9.0"
    },
    "dependencies": {
      "react": "^15.4.2",
      "react-dom": "^15.4.2",
      "react-redux": "^4.3.0",
      "react-router": "^2.0.0",
      "redux": "^3.2.1",
      "react-router-redux": "^4.0.0"
    },
    "scripts": {
      "start": "react-scripts start",
      "build": "react-scripts build",
      "test": "react-scripts test --env=jsdom",
      "eject": "react-scripts eject"
    }
  }

Styles aren't applied on the component, but it's works if I rewrite AvatarHeader.js so:

  import styles from './AvatarHeader.css';

  const image = {
    width: 400
  }

  export default function AvatarHeader({ style, children }) {
    return (
      <div>
        <img style={image} src={Background} alt="background">
          { children }
        </img>

I don't understand how to fix this bug for use the first way to import css file.

import './AvatarHeader.css';`
<img className='image' />` 

is the correct syntax

In case anyone runs into this problem again, the stylesheet needs to follow the module naming convention for the OP's original syntax to work.

So once the file is renamed AvatarHeader.module.css , the following React code should work:

import styles from './AvatarHeader.module.css';

export default function AvatarHeader({ style, children }) {
  return (
    <div>
      <img style={styles.image} src={Background} alt="background">
        { children }
      </img>

You need to change the CSS file name from AvatarHeader.css to AvatoarHeader.module.css . then the import statement should be: import styles from './AvatarHeader.module.css' . It should work now. see docs

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