【问题标题】:I would like to style JS file in react using CSS styling but I'm getting an error我想使用 CSS 样式设置 JS 文件的样式,但出现错误
【发布时间】:2021-04-28 03:11:42
【问题描述】:
import React from 'react'
import './myStyle.css'
function Stylesheet(){
    return(
        <div>
            <h1>Stylesheet</h1>
        </div>
    )
}
export default Stylesheet

我遇到了一个错误

./src/Components/stylesheet.js Module not found: Can't resolve './myStyle.css' in 'D:\Documents\WebProject\React\hello-world\src\Components'

【问题讨论】:

  • 你在使用 create-react-app 吗?文件“myStyle.css”是否存在?

标签: javascript css reactjs


【解决方案1】:

无需创建组件来设置组件的样式。只需编写您的 css 样式并像 import './myStyle.css' 一样导入它

【讨论】:

    【解决方案2】:

    React 组件的样式有不同的选项。我将在这里解释几个选项。

    CSS 样式表:

    如下添加Stylesheet.css 文件。

    .boxColor {
      background-color: red;
    }
        
    

    添加组件Stylesheet.js。只需导入css文件import './Stylesheet.css'

    import React from 'react';
    import './Stylesheet.css';
    
    const Stylesheet = () => (
      <div className="boxColor">
        <p>Get started with CSS styling</p>
      </div>
    );
    
    export default Stylesheet;
    

    内联样式:在 React 中,内联样式不指定为字符串。相反,它们是用一个对象指定的。

    添加Stylesheet.js 文件。

    import React from 'react';
    
    const boxColor = {
      background-color: red;
    };
        
    const Stylesheet = () => (
     <div style={boxColor}>
       <p>Get started with CSS styling</p>
     </div>
    );
        
    export default Stylesheet;
    
    • 我们可以创建一个存储样式属性的变量,然后通过 像style={boxColor}这样的元素
    • 我们也可以直接传递样式style={{background-color: 'red'}}

    Styled-componentCSS Modules 之类的其他方式可以为 react 组件设置样式。

    【讨论】:

      【解决方案3】:

      例如,您有两个文件,第一个是 practice.js,第二个是 style.css 然后将您的 style.css 导入practice.js 如下。

      practice.js 文件

      import React from 'react';
      import './style.css'; //importing style sheet
      
      export default function practice() {
           return (
                <div>
                     <h1 className="heading">Hellooooooo</h1>    
                </div>
           )
      }
      

      你的 style.css 文件是

      .heading{
           color: white;
           background-color:  black;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-30
        • 2021-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多