是否可以在自定义反应组件上设置className? [英] Is it possible to set a className on custom react components?

查看:48
本文介绍了是否可以在自定义反应组件上设置className?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个像这样的简单组件:

Let's say I have a simple component like this:

class SimpleComponent extends React.Component
{
    render() { return <p>Some text</p> }
}

是否可以在 SimpleComponent 中添加 className ,还是仅将其限制为HTML DOM元素?

Is it possible to add a className to SimpleComponent or is this constrained to HTML DOM elements only?

例如:

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;
}

推荐答案

可以,但是应该将prop传播到内部组件.如果不是这样,那就不知道了.

You can, but you should propagate the prop to the inner component. If not, it doesn't know about it.

class SimpleComponent extends React.Component
{
    render() { return <p className={this.props.className}>Some text</p> }
}

要进行要完成的CSS查询,则应在组件内部创建 div .

To make the CSS query you want to accomplish, then you should create the div inside your component.

class SimpleComponent extends React.Component
{
    render() { return <div className={this.props.className}><p>Some text</p></div> }
}

这篇关于是否可以在自定义反应组件上设置className?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆