React-尝试将SVG填充颜色作为Prop传递,而在背景图像属性中使用SVG作为数据?

发布于 2025-02-04 08:28:35 字数 941 浏览 3 评论 0原文

我希望动态地更改我用作容器中背景图像属性的SVG图案的填充颜色。我正在通过使用数据URI并将SVG代码作为样式组件中的值直接进行此操作。目前,它无法识别道具,模式只是消失。当我将填充颜色作为静态值起诉时,这起作用。是我写的方式吗?

这里有一些代码 -

import React, { useState } from "react";
import styled from "styled-components";
import './App.css';

const Container = styled.div`
   height: 50vh;
   width: 100%;
   background-color: ${props => props.bg};
   background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='${props => props.color}' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath d='M5.25 0l-4 4 4 4 1.5-1.5L4.25 4l2.5-2.5L5.25 0z'/%3e%3c/svg%3e");
   background-size: cover;
`;


function App() {
   const [color, setColorChosen] = useState("green");
   const [bgChosen, setbgChosen] = useState("yellow");
   
  return (
     <>
         <Container bg={bgChosen} color={color}>
            
         </Container>
      </>
  );
}
export default App;

I wish to dynamically change the fill color of a svg pattern that I'm using as a background image property in a container. I am doing this through using the data uri and directly injecting the SVG code as a value in a styled component. Currently it won't recognise the prop and the pattern just disappears. This works when I sue the fill color as a static value. Is it the way I wrote it?

Here some code -

import React, { useState } from "react";
import styled from "styled-components";
import './App.css';

const Container = styled.div`
   height: 50vh;
   width: 100%;
   background-color: ${props => props.bg};
   background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='${props => props.color}' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath d='M5.25 0l-4 4 4 4 1.5-1.5L4.25 4l2.5-2.5L5.25 0z'/%3e%3c/svg%3e");
   background-size: cover;
`;


function App() {
   const [color, setColorChosen] = useState("green");
   const [bgChosen, setbgChosen] = useState("yellow");
   
  return (
     <>
         <Container bg={bgChosen} color={color}>
            
         </Container>
      </>
  );
}
export default App;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心欲静而疯不止 2025-02-11 08:28:35

我不确定为什么它不适合您,它对我有用。
您正在使用JS还是TS?我也可以看到错误消息吗?

I am not sure why it's not working for you, it works for me.
Are you using JS or TS? can I see the error message too?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文