【问题标题】:How to style one react component inside another?如何在另一个内部设置一个反应组件的样式?
【发布时间】:2016-06-07 06:08:43
【问题描述】:

我是 CSS 新手,我不知道如何在 React 中将一个组件放置在另一个组件中。我可以单独展示它们,但是当我把它们放在另一个里面时。我没有看到里面的那个。我认为问题出在css文件中

#homePage{
   section{
      h1{
        text-align: left; //this is shown
      }
      //here I want to add the other React component but I don't know how

   }
}

以及渲染方法:

<div id="homePage">
  <Component1>
    <section>
     <h1>Hi</h1>
     <Component2>
     </Component2>
    </section>
  </Component1>
</div>

谢谢。

【问题讨论】:

  • 嗨,关于将样式应用于 react 中的嵌套组件的问题是什么?还是将一些组件放在另一个组件中?
  • 它只是另一个组件中的一个组件
  • 请发布更多代码

标签: css reactjs styles


【解决方案1】:

据我了解,您可以在 Component2 的 HTML 标记中定义 className 属性。

class Component2 extends Component{ 

render(){

    return(
        <section className="component2styles">
            This is Component2
        </section >
    );
} }

现在,您可以将样式表更改为

#homePage{
   section{
      h1{
        text-align: left; //this is shown
      }
      //components2 style will be nested here

     section.component2styles{
       border:1px solid blue;
     }

   }
}

或者作为替代方案,您可以尝试 inline-styles ,似乎在 React 开发中获得了很大的吸引力。

render(){
 var styleobj={color:'red'};
 return( <section style={styleobj} > This is Component 2 </section> ) 
}

【讨论】:

    【解决方案2】:

    您是否在 Component2 中添加了一些类/id,例如 &lt;Component2 className="my-specific-class" /&gt; 来设置样式?

    (顺便说一句,我希望你的 css 更少/sass 允许像你一样嵌套样式)

    编辑 通过添加 className attr。到您的 Component2,我的意思是将其添加到 Component2 渲染方法中,例如

    render: function() {
        return (
            <div id="your-id" className="your-class">
                some html here
            </div>
        );
    }
    

    【讨论】:

    • 是的,这很无耻。不,我没有添加 id 或 className。但是当我尝试添加它时,它说 className 不存在。我应该将它添加为 component2 中的道具吗? p.s.我对这一切都不熟悉
    • 是的,我的例子并不完整。如果您的 Component2 渲染方法返回类似 &lt;div&gt;some html here&lt;/div&gt; 的内容,您应该添加类似 &lt;div id="..." className="..."&gt;some html here&lt;/div&gt; 的 className 属性(我将编辑我的答案以避免将来产生误解 :)!)
    • 是的,但我的问题是我应该以及如何在#homePage 中添加这个组件。谢谢
    • 能否复制/粘贴您的 React 代码和/或呈现的 html?
    • 您的代码可能有问题的是您执行嵌套组件的方式。我试图避免这种情况(而且我没有看到你的整个代码,所以可能不是这样),但看看这个:stackoverflow.com/questions/29020863/…
    猜你喜欢
    • 2019-10-18
    • 2022-11-13
    • 2020-10-23
    • 2018-03-19
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 2020-12-27
    • 2014-11-05
    相关资源
    最近更新 更多