:: after不适用于React道具,但适用于常规文本

I have a react component that gets some properties. One of them is altText. I want my div to have an ::after, with content being the prop altText.

我尝试了类似的东西(样式组件):

const StyledImage = styled.div`
    &::after {
        content: ${props => props.altText};
        color: black;
    }
`;

//

export const Image = ({src, altText, size, scale}) => {
    const imageProps = {
        src: src,
        altText: altText,
        size: size,
        scale: scale,
    }

    return (
        <StyledImage {...imageProps}>
            <img src={imageProps.src} alt={imageProps.altText}/>
        </StyledImage>
    )
}

(I'm not talking about the alt of the img, it's something else)

我将此组件称为如下:

<Image src="https://p.bigstockphoto.com/GeFvQkBbSLaMdpKXF1Zv_bigstock-Aerial-View-Of-Blue-Lakes-And--227291596.jpg" altText="hello"/>

That doesn't work. However when I change content: ${props => props.altText}; to content: 'hello' it works perfectly fine. I made sure that altText is a string an it is.

这是什么问题

评论
  • 小自摸
    小自摸 回复

    You need to use &:after instead of &::after

    const StyledImage = styled.div`
        &:after {
            content: ${props => props.altText};
            color: black;
        }
    `;
    
    //
    
    export const Image = ({src, altText, size, scale}) => {
        const imageProps = {
            src: src,
            altText: altText,
            size: size,
            scale: scale,
        }
    
        return (
            <StyledImage {...imageProps}>
                <img src={imageProps.src} alt={imageProps.altText}/>
            </StyledImage>
        )
    }