我一直在學習 React 并練習一些基本的東西,這可能是一個非常簡單的問題,有一個更簡單的解決方案,但對于我的生活,我在谷歌上找不到我需要的東西。
基本上我有這段代碼:
export default function BigContainer({ rain, icon, temperature, date }) {
return (
<div className='bigContainer'>
<Container rain={rain[0]} icon={icon[0]} temperature={temperature[0]} date={date[0]} />
<Container rain={rain[1]} icon={icon[1]} temperature={temperature[1]} date={date[1]} />
<Container rain={rain[2]} icon={icon[2]} temperature={temperature[2]} date={date[2]} />
</div>
)
}
有問題的變數是簡單的陣列,其中包含數字或字串,沒有什么真正重要的。
而且我一直在尋找一種不必在每個屬性的索引中硬編碼的方法,因為硬編碼這些東西并不理想。
我已經嘗試映射其中一個陣列,但我對如何實作與我正在映射的一個陣列相關的其他屬性有點困惑,所以我無法讓它作業。
所以,是的,如果有辦法做喜歡
Loop the stuff here{
<Container rain={rain[i]} icon={icon[i]} temperature={temperature[i]} date={date[i]} />
}
或類似的東西,它基本上是我正在尋找的東西。先感謝您。
uj5u.com熱心網友回復:
試試這個,你可以用你想要映射的陣列替換 [1,2]
[1,2].map((item,index)=>
<Container rain={rain[index]}
icon={icon[index]}
temperature={temperature[index]}
date={date[index]} />
)
uj5u.com熱心網友回復:
這不是在反應中呈現動態值的最佳方式。首先,您需要將值放入物件中。
//For example put them in an array called weather and put the values
inside with key-value pairs. Then you can easily loop the values.
export default function App() {
return (
<div className="bigContainer">
{weather.map((value) => (
<table>
<tr>
<th>rain</th>
<th>temperature</th>
<th>date</th>
</tr>
<tr>
<td>{value.rain}</td>
<td>{value.temperature}</td>
<td>{value.date}</td>
</tr>
</table>
))}
</div>
);
}
uj5u.com熱心網友回復:
您也可以只傳遞一個物件陣列,而不是單獨傳遞陣列,因為它們彼此相關
const weather = [
{
rain: 'rain1',
icon: 'icon1',
temperature: 'temp1',
date: 'date1',
},
{
rain: 'rain2',
icon: 'icon2',
temperature: 'temp2',
date: 'date2',
},
{
rain: 'rain3',
icon: 'icon3',
temperature: 'temp3',
date: 'date3',
},
]
{weather.map((item, key) => (
<div key={key} className='bigContainer'>
<Container rain={item.rain} icon={item.icon} temperature={item.temperature} date={item.date} />
</div>
))}
并像這樣映射它們
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/487524.html
標籤:javascript 反应 jsx
