[英]How can I customize the checked state of a checkbox when using svgr in React?
I'm working on a React
project and I'm using styled-component
and typescript
.我正在开发一个React
项目,我正在使用styled-component
和typescript
。
I'm customizing the checkbox like this:我正在像这样自定义复选框:
import React, { ReactElement } from 'react';
import styled from 'styled-components';
import IconChecked from '@assets/Icons/ico_checked.svg';
interface Props {
id: string;
}
const StyledCheckBox = styled.input`
box-sizing: border-box;
width: 20px;
height: 20px;
background: #ffffff;
border: 1px solid #d4dae4;
border-radius: 4px;
appearance: none;
&:checked {
background-image: url(${IconChecked});
background-repeat: no-repeat;
background-color: #ffffff;
background-position: 50%;
}
`;
const CheckBox = ({ id }: Props): ReactElement => (
<StyledCheckBox type="checkbox" id={id} />
);
export default CheckBox;
To use the svg icon without the <img>
tag, I installed the svgr
package and set it as an svg type loader through webpack
. To use the svg icon without the <img>
tag, I installed the svgr
package and set it as an svg type loader through webpack
. The problem is that svgr
has the logic to convert svg to component, so I can't set the checked icon in the following way.问题是svgr
具有将 svg 转换为组件的逻辑,所以我无法通过以下方式设置选中的图标。
&:checked {
background-image: url(${IconChecked});
...
}
As a result, the check icon( IconChecked
) does not appear when I click the checkbox after using svgr
.结果,使用svgr
后单击复选框时,不会出现检查图标( IconChecked
)。 How can I solve this?我该如何解决这个问题?
You can move your ico_checked.svg
file to public
folder and use the svg directly from the url like this:您可以将您的ico_checked.svg
文件移动到public
并直接从 url 使用 svg,如下所示:
&:checked {
background-image: url("/ico_checked.svg");
...
}
You can take a look at this sandbox for a live working example of this approach.您可以查看此沙箱,了解此方法的实时工作示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.