【问题标题】:How to get access to the children's css values from a styled component?如何从样式化组件访问子级的 css 值?
【发布时间】:2019-01-24 16:59:00
【问题描述】:

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

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

const StyledCalendar = styled(Calendar);

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

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

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

【问题讨论】:

  • getComputedStyle 如果你给它正确的元素应该可以工作。你是如何选择elem的?
  • 我给它的元素是 StyledCalendar,因为这是我在这个类中唯一可以访问的组件。我使用了 refs,我的问题是如何从子组件中获取这些样式。我正在覆盖作为库的 RBC。

标签: css reactjs node-modules styled-components react-big-calendar


【解决方案1】:

您可以使用简单的字符串插值来做到这一点,只需确保 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>
)

查看更多here

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 非常感谢您的帮助!反正有没有用裁判做这个?再次感谢
    • 您必须在子组件上设置一个 ref,但您说您无权访问它,所以这会很困难。如果您确定父级中 html 的结构,则可以对父级进行引用,然后使用 .children 之类的内容导航到所需的元素,但这有点笨拙。跨度>
    猜你喜欢
    • 1970-01-01
    • 2022-01-18
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    相关资源
    最近更新 更多