首页 > 解决方案 > 使用特异性级别为 1 的 styled-components 定位子元素

问题描述

场景是我有一个组件,即<BrandLogo />使用底层<a>元素进行样式设置。该组件还具有一个img子元素。styled-components有没有一种方法可以在具有特异性级别 1的帮助下为子元素创建样式。

我知道我可以直接使用styled-components.

方法一:

import React from 'react';
import styled from 'styled-components';


const BrandLogo = styled.a`
    color: #1a1c1c;
    display:inline-block;
    vertical-align:top; 
    img {
    display:block;
    }
`;

const App = () => {

    return (<div style={{backgroundColor: '#e6e6e6'}}>
        <BrandLogo href="/">
            <img src="https://dcstatic.com/images/brandcrowd/logos/brandcrowd-logo-5d59400c52.svg" alt="BrandCrowd"/>
        </BrandLogo>
    </div>)
};

export default App;

将生成以下标记:

<div style="background-color: rgb(230, 230, 230);">
        <a class="sc-bdVaJa gdDbnn" href="/"><img alt="BrandCrowd" src="https://dcstatic.com/images/brandcrowd/logos/brandcrowd-logo-5d59400c52.svg"></a>
    </div>

但是img元素的特异性是2级。

.gdDbnn img {
    display: block;
}

方法二:

将元素创建img为样式组件,但现在它被视为组件。是的,这种方法将创建具有 1 级特异性的样式。

但是是否有任何其他方法可以对具有特异性级别 1 的子组件进行样式设置。

标签: reactjsstyled-components

解决方案


推荐阅读