javascript 是否可以在自定义反应组件上设置 className?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46040733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to set a className on custom react components?
提问by sookie
Let's say I have a simple component like this:
假设我有一个像这样的简单组件:
class SimpleComponent extends React.Component
{
render() { return <p>Some text</p> }
}
Is it possible to add a classNameto SimpleComponentor is this constrained to HTML DOM elements only?
是否可以添加className到SimpleComponent或仅限于 HTML DOM 元素?
For example:
例如:
var mySimpleComponent = <SimpleComponent className="myComp"/>
The reason I would like to do this is so that I can style the elements inside my custom component like this:
我想这样做的原因是,我可以像这样设置自定义组件中的元素样式:
.myComp > p {
background-color: blue;
}
回答by jorgonor
You can, but you should propagate the prop to the inner component. If not, it doesn't know about it.
你可以,但你应该将 prop 传播到内部组件。如果没有,它不知道它。
class SimpleComponent extends React.Component
{
render() { return <p className={this.props.className}>Some text</p> }
}
To make the CSS query you want to accomplish, then you should create the divinside your component.
要进行您想要完成的 CSS 查询,您应该div在组件内部创建。
class SimpleComponent extends React.Component
{
render() { return <div className={this.props.className}><p>Some text</p></div> }
}

