如何将React.Component放入CSS内容属性(在伪元素之前/之后)



styled-components中,我试图通过content让React图标在悬停时渲染,但由于某种原因,我在悬停时的渲染是[Object Object]

组件:

export const FooLink = styled(Link)`
padding: 0.5rem 2rem;
color: ${({ theme }) => theme.colors.white};
text-align: center;
margin: 0 auto;
position: relative;
font-size: ${({ theme }) => theme.fontSizes.p};
letter-spacing: 0.15em;
transition: ${({ theme }) => theme.animations.trans3};
&:after {
content: '${FaArrowRight}';
/* content: '>'; */
position: absolute;
opacity: 0;
right: -${({ theme }) => theme.spacings.small};
transition: ${({ theme }) => theme.animations.trans3};
}
&:hover {
padding-right: ${({ theme }) => theme.spacings.small};
padding-left: ${({ theme }) => theme.spacings.xxSmall};
}
&:hover:after {
opacity: 1;
${({ theme }) => theme.spacings.xSmall};
}
`

我把所有东西都带来了:

import styled from 'styled-components'
import { Link } from 'gatsby'
import { FaArrowRight } from 'react-icons/fa'

对内容的其他尝试

content: ${FaArrowRight};

但我发现这不起作用:

这是因为内容值必须在CSS中的引号内。

意识到我可能在CSS精神状态下花了太长时间,我尝试引入React:

import React from 'react'
import styled from 'styled-components'
import { Link } from 'gatsby'
import { FaArrowRight } from 'react-icons/fa'

和渲染:

content: '${(<FaArrowRight />)}';

当我尝试使用模板文字时,我会遇到一个缺少分号的错误:

content: `'${<FaArrowRight />}'`;

所有尝试均显示为[Object Object]

研究一下是否有人问过这个问题,我已经通读了:

  • 如何在样式组件中动态呈现pseudo-before-content
  • 与样式化组件一起使用的Before和After伪类
  • 反作用内联样式中的css伪代码"li::before">
  • 如何将graphQl查询中的变量转换为内联样式或样式组件中的伪元素
  • psuedo选择器在样式组件中的工作方式是否与使用unicode字符的css相同

styled-components中,如何在content中渲染React图标?

如果您需要将styled-components(或JS库中的任何其他CSS(与react-icons(或任何其他导出React.Component并呈现<svg>元素的库(中的图标一起使用,我认为只有一种方法:使用标记字符串将组件转换为url(),因为只有这样,您才能将图像传递给content属性。对于该转换,您需要:React.createElement()ReactDOMServer.renderToStaticMarkup()encodeURIComponent()。此外,您也可以使用Base64。

这个有效(CodeSandbox(:

import { createElement } from "react";
import { render } from "react-dom";
import { renderToStaticMarkup } from "react-dom/server";
import styled from "styled-components";
import { Link } from "gatsby";
import { FaArrowRight } from "react-icons/fa";
window.___loader = { enqueue: () => {}, hovering: () => {} };
const reactSvgComponentToMarkupString = (Component, props) =>
`data:image/svg+xml,${encodeURIComponent(
renderToStaticMarkup(createElement(Component, props))
)}`;
const FooLink = styled(Link)`
${({ color }) => color && `color: ${color};`}
&:after {
content: ${({ color }) =>
`url(${reactSvgComponentToMarkupString(FaArrowRight, {
color
})})`};
position: absolute;
opacity: 0;
}
&:hover:after {
opacity: 1;
}
`;
render(
<>
<div>
<FooLink to="/test1" color="red">
Link with arrow (red)
</FooLink>
</div>
<div>
<FooLink to="/test2">Link with arrow (default)</FooLink>
</div>
</>,
document.getElementById("root")
);

感谢这个Github Gist。

最新更新