[英]How to render SVG images inside a div
我是新手,希望有人能幫助我。 我到處尋找解決我的問題的方法,但沒有運氣。
基本上我想在一個 div 中渲染一個包含 SVG 個圖像的數組作為背景圖像:url()。 我已經設法用 math.random 渲染我的數組,但我希望 SVG 圖像以與數組中相同的順序渲染。
到目前為止,這是我的代碼:
import './ListView.css';
import Green from '../Assets/ListCard/Green.svg';
import Brown from '../Assets/ListCard/Brown.svg';
import Orange from '../Assets/ListCard/Orange.svg';
import Mail from '../Assets/Icons/Mail.svg'
import Phone from '../Assets/Icons/Phone.svg'
function ListView({ userData}) {
const cardImages = [Green, Brown, Orange]; /// Array
const renderList = cardImages.map(function(image) { /// Tried to map through the array with -
return image; /// no luck
})
/// This Math.radom method works, but not the solution i want
const randomItem = cardImages[Math.floor(Math.random()*cardImages.length)];
return ( /// Below inside the div is where i want to render the images.
<div className="list-card" style={{backgroundImage: `url(${renderList})`}}>
<div className="list-card-wrapper">
<div className="list-user-image"><img src={userData.picture.medium} alt=""/></div>
<div className="list-user-info">
<div className="list-user-name">{userData.name.first} {userData.name.last}</div>
<div className="list-user-location">{userData.location.city}</div>
</div>
<div className="list-user-contact">
<img height={19} src={Mail} alt="svg"/>
<img height={19} src={Phone} alt="svg"/>
</div>
</div>
</div>
)
}
export default ListView```
您將需要導入圖像並像下面那樣綁定它:
import logo from './logo.svg';
function App() {
return (
<div className="App">
<img src={logo} className="App-logo" alt="logo" />
</div>
);
}
export default App;
這就是您可能正在尋找的:
import "./styles.css";
export default function App() {
const items = [
{ name: "first" },
{ name: "second" },
{ name: "third" },
{ name: "fourth" },
{ name: "fifth" },
{ name: "sixth" }
];
const colorArray = ["green", "brown", "orange"];
return (
<div className="App">
{items.map((item, index) => {
const classColorIndex = index % 3;
return (
<div
className={`list-card ${colorArray[classColorIndex]}`}
key={index}
>
<p>{item.name}</p>
</div>
);
})}
</div>
);
}
這背后的主要概念是,您必須關注項目的索引並檢查它是first
、 second
還是third
項目(我認為它是 3,因為數組中有 3 個 colors)。 現在,根據索引號,您需要向該 div 添加一個 class,並使用 CSS,您可以根據該數組為每個 div 提供背景。
在此示例中,我使用了純背景色,但我也說明了如何使用 svg。 在 APP.css 上,這里是 css
.App {
font-family: sans-serif;
text-align: center;
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
.list-card {
width: 50px;
height: 50px;
display: flex;
justify-content: center;
flex-basis: 50%;
}
.list-card.green {
background: green;
/* background:url('../../Green.svg'); */
}
.list-card.brown {
background: brown;
}
.list-card.orange {
background: orange;
}
這是沙盒鏈接:
https://codesandbox.io/s/stack-overflos-sample-z0yxyk?file=/src/App.js
在這個例子中,你可以看到背景被分配給了數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.