猿问

为什么我的 CSS 文件适用于每个 React 组件?

背景:


我正在制作一个具有登录组件、注册组件、应用程序组件、食谱组件和 recipe_tile 组件的食谱应用程序。


我有三个 CSS 文件:Registration.CSS、Login.CSS 和 APP.CSS。前两个 css 文件分别用于注册和登录组件。而 APP.CSS 文件用于 app、recipe 和 recipe_tile 组件。


问题:


问题是某些 CSS 选择器,如背景(包含背景图像)显示在每个组件中,尽管相关的 CSS 文件已导入组件。例如,Registration.CSS 是唯一导入注册组件的 CSS 文件。


我知道一个可能的解决方案是在每个组件中使用内联样式,但这可能很乏味且难以阅读。我可以做任何其他可能的解决方案吗?


注册.CSS 文件:


*{

    margin: 0

}

body{

    font-family: "Open Sans", sans-serif;

    top: 0;

    left: 0;

    background: 

    linear-gradient(

        rgba(0, 0, 0, 0.45), 

        rgba(0, 0, 0, 0.45)

      ),

    url("https://i.imgur.com/9MDiW6B.jpg") 70% fixed;

  background-size: cover;

}


.box{

    color:#26a69a;

    display: flex;

    align-items: center;

    flex-direction: column; 

    justify-content: center;

    width: 40%;

    height: 600px;

    padding: 100px;

    background: #ffffff;

    margin-left: 30%;

    margin-top: 5%;

}

登录.CSS 文件:



.wrap{

    font-family: "Open Sans", sans-serif;

    top: 0;

    left:0;

    background: 

    linear-gradient(

        rgba(0, 0, 0, 0.45), 

        rgba(0, 0, 0, 0.45)

      ),

    url("https://i.imgur.com/9MDiW6B.jpg") 70% fixed;

  background-size: cover;

}


.wrap{

    color:#26a69a;

    display: flex;

    align-items: center;

    flex-direction: column; 

    justify-content: center;

    width: 40%;

    height: 400px;

    padding: 100px;

    background: #ffffff;

    margin-left: 30%;

    margin-top: 5%;

}

APP.CSS 文件:


*{

  margin-left: 15px;

}

h1{

  color:#26a69a

}

.inputs{

  margin-left: 400px;

}

.recipe-input{

  width: 50%;

}

.button-input{

  margin-top: 30px

}

.card{

  display: inline-block;

  margin: 2px 100px 60px 2px;

  text-align: center;

  width: 25%;

  height: 460px; 

}

.card-image{

  display: block;

  margin-left: -15px;


  width: 105%;

  height: 250px;

}

.card-reveal{

  text-align: left;

}


这是完整的源代码:https ://github.com/SibRaza15/recipe_app/tree/master/src


喵喔喔
浏览 159回答 2
2回答

函数式编程

我看到了多种反模式。根据经验,不要*用于样式,因为您会遇到像这样的问题。相反,为该类名中的每个组件和样式创建一个类名,以保持所有内容分开。我看到您Register.css的目标是整个文档正文,它应该只是在Register.js组件中设置样式。我说的是做类似的事情:Foo.jsimport React from 'react'import './Foo.css'const Foo = (props) => {&nbsp; return (&nbsp; &nbsp; <div className="foo">&nbsp; &nbsp; &nbsp; <h4>whatever</h4>&nbsp; &nbsp; </div>&nbsp; &nbsp;)}export default Foo;Foo.css.foo {&nbsp; ... style here}.foo h4 {&nbsp; ... style other components or tags inside of foo}此外,App.css仅保留绝对全局的样式,例如字体类型和链接颜色等。不要尝试从那里设置单个组件的样式。

动漫人物

我不相信 CSS 可以按照您的想法从基本 HTML 文件中动态加载和卸载。一旦它被加载,它就会被加载到 HTML 中。对于您的问题,我可以想到两种解决方案:为组件指定类名,以便其他 CSS 选择器不会干扰。在 JS 解决方案中使用 CSS,其中一个组件将有自己的样式,您不必担心全局范围的 CSS 选择器会干扰。最流行的是styled-components。在 JS 解决方案中切换到 CSS 的最大优势是您可以将 props 直接传递给样式化组件(即样式化 div),并具有用于动态样式的 JavaScript 样式逻辑。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答