我正在嘗試映射作為 prop 傳遞的物件,并希望為不同的物件值顯示不同的 HTML 元素
目的;
const allDesc = {description: "Title Description", description1: "Intro
Description", description3:"Sub title", description3: "Sub Description"}
代碼:
<div>
{Object.keys(allDesc).map((desc, index) => {
if (allDes[desc] !== "") {
return (
<>
<h1>allDesc.description</h1>
<p>allDesc.description1</p>
<h3>allDesc.description2</h3>
<p>allDesc.description3</p>
</>
);
}
})}
</div>
這種方法什么都不顯示,什么是映射物件并為不同物件值顯示不同 HTML 元素的正確方法。謝謝!
uj5u.com熱心網友回復:
map在Object.entries. 如果鍵匹配“描述” <h1>,則將值作為 a 回傳,否則將值作為 a 回傳<p>。
function Example({ allDesc }) {
return (
<div>
{Object.entries(allDesc).map(([key, value]) => {
if (key === 'description') return <h1>{value}</h1>;
if (key === 'description3') return <h3>{value}</h3>;
return <p>{value}</p>;
})}
</div>
);
};
const allDesc = {description: 'Title Description', description1: 'Intro Description', description3: 'Another Description', description4: 'More text' };
ReactDOM.render(
<Example allDesc={allDesc} />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
uj5u.com熱心網友回復:
請試試這個。
<div>
{Object.keys(allDesc).map((desc, index) => {
if (allDes[desc] !== "") {
return (
<>
{
desc === 'description' ? <h1>allDes[desc]</h1> :
<p>allDes[desc]</p>
}
</>
);
}
})}
</div>
這allDes[desc]具有您從物件鍵回圈的所有欄位的值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/355556.html
標籤:javascript 反应 映射
