React-尝试将SVG填充颜色作为Prop传递,而在背景图像属性中使用SVG作为数据?
我希望动态地更改我用作容器中背景图像属性的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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(1)
我不确定为什么它不适合您,它对我有用。
您正在使用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?