0

我正在使用一个 REACT BIG CALENDAR,我想在我的一个函数中访问 c​​ss 值。

我创建了一个样式组件并覆盖了库

const StyledCalendar = styled(Calendar);

现在,例如,日历中有一个 div,其 class = "hello",

如何在函数中访问“hello”的 css 值?类似于在手写笔中的属性查找。

我已经尝试过window.getComputedStyle(elem, null).getPropertyValue("width"),但这给出了父组件的 css。

4

2 回答 2

0

如果您知道类名,您应该能够选择它并将该元素提供给 getComputedStyle 而不是给它 StyledCalendar。就像是:

const childElement = document.getElementsByClassName('hello')[0];
const childWidth = getComputedStyle(childElement).getPropertyValue('width');

(这假设页面上只有一个类为“hello”的元素,否则您必须找出您想要的元素在 getElementsByClassName 返回的节点列表中的位置)

于 2018-08-17T18:09:52.680 回答
0

您可以使用简单的字符串插值来做到这一点,只需确保将className其传递给Calendar的根元素。

像这样:

const StyledCalendar = styled(Calendar)`
    .hello {
       color: red;
    }
`

日历组件

const Calendar = props => (

    // I don't know exact how this library is structured
    // but need to have this root element to be with className from props 
    // if it's possible to pass it like this then you can do it in this way
    <div className={props.className}>
       ...
       <span className="hello"> Hello </span>
       ...
    </div>
)

在这里查看更多。

于 2018-08-17T17:07:45.900 回答