通过组件的displayName是否应用CSS?

时间:2019-06-25 14:01:12

标签: javascript html css reactjs css-selectors

致电所有专家!

我正在尝试添加一个类以禁止所有元素的后代为只读,这种样式还不错,但是它不适用于所有后代,也不适用于任何情况:

#ComponentDisplayName * {
    -webkit-user-select: text;
    -moz-user-select: text;
    -ms-user-select: text;
    user-select: text;
    pointer-events: none;
}

该元素是一个component,我想通过displayName作为div id来具有上述样式,就像这样:

import * as readOnly from './Permission.scss';

<div
    id={component.type.displayName}
    className={readOnly[component.type.displayName]}
>
    {React.createElement(component, {
        ...component.className
    })}
</div>

输出HTML:

enter image description here

最终结果应显示该组件对其所有子组件都具有样式层叠。

有可能吗?

提前感谢所有参与者。

1 个答案:

答案 0 :(得分:0)

看来我根本不需要使用id属性。将类规则定义为displayName就足够了:

.ComponentDisplayName * {
    -webkit-user-select: text;
    -moz-user-select: text;
    -ms-user-select: text;
    user-select: text;
    pointer-events: none;
}

然后,您可以使用组件的displayName选择样式,如下所示:

import * as readOnly from './Permission.scss';

<div className={readOnly[component.type.displayName]}>
    {React.createElement(component, {
        ...component.className
    })}
</div>

最后,样式将应用于组件的所有后代元素。