如何在一个反应组件中设置另一个组件的样式?
How to style one react component inside another?
我是 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>
谢谢。
您是否向您的 Component2 添加了一些 class/id,例如 <Component2 className="my-specific-class" />
来设置样式?
(顺便说一句,我希望你的 css 是 less/sass 一个像你一样允许嵌套样式的人)
编辑
通过添加 className 属性。到您的 Component2,我的意思是将其添加到 Component2 渲染方法中,例如
render: function() {
return (
<div id="your-id" className="your-class">
some html here
</div>
);
}
据我了解,您可以在 Component2 的 HTML 标签中定义 className 属性。
class Component2 extends Component{
render(){
return(
<section className="component2styles">
This is Component2
</section >
);
} }
现在,您可以将您的样式 sheet 更改为
#homePage{
section{
h1{
text-align: left; //this is shown
}
//components2 style will be nested here
section.component2styles{
border:1px solid blue;
}
}
}
或者作为替代方案,您可以尝试内联样式,它似乎在 React 开发中获得了很大的关注。
render(){
var styleobj={color:'red'};
return( <section style={styleobj} > This is Component 2 </section> )
}
我是 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>
谢谢。
您是否向您的 Component2 添加了一些 class/id,例如 <Component2 className="my-specific-class" />
来设置样式?
(顺便说一句,我希望你的 css 是 less/sass 一个像你一样允许嵌套样式的人)
编辑 通过添加 className 属性。到您的 Component2,我的意思是将其添加到 Component2 渲染方法中,例如
render: function() {
return (
<div id="your-id" className="your-class">
some html here
</div>
);
}
据我了解,您可以在 Component2 的 HTML 标签中定义 className 属性。
class Component2 extends Component{
render(){
return(
<section className="component2styles">
This is Component2
</section >
);
} }
现在,您可以将您的样式 sheet 更改为
#homePage{
section{
h1{
text-align: left; //this is shown
}
//components2 style will be nested here
section.component2styles{
border:1px solid blue;
}
}
}
或者作为替代方案,您可以尝试内联样式,它似乎在 React 开发中获得了很大的关注。
render(){
var styleobj={color:'red'};
return( <section style={styleobj} > This is Component 2 </section> )
}