对React with map方法有一个问题



我现在正在学习React。我有一个关于地图方法的问题。productName1和productName2有什么不同吗?(li部分除外)

const productName1 = arr.map(a =><li>{a.name}</li> );
const productName2 = arr.map(a =>a.name );

谢谢。

const arr = Data;

// console.log(arr);

const productName1 = arr.map(a =><li>{a.name}</li> );
const productName2 = arr.map(a =>a.name );
console.log(productImage);
return (
<div className="contents">   
<h1>Please Select Products</h1>      
<h3>{productName1}</h3>
<h3>{productName2}</h3>
</div>
)
}
export default ProductData

是的,它们是不同的,假设你的数组是这样的:

const arr = [
{name: "John"},
{name: "Jane"},
{name: "Jim"}
]

productName1中生成的html是这样的:

<h3>
<li>John</li>
<li>Jane</li>
<li>Jim</li>
</h3>

在react中相当于一个JSX数组。JSX。元素[]

而productName2的结果将是:

<h3>JohnJaneJim</h3>

它只是一个字符串数组,将被输入如下string[]

所以基本上在productName1中,你正在创建包含名称的li标签元素,这是创建无效的html,因为你需要将li项目包装在ol标签或ul标签内。productName2只生成一个字符串数组,这些字符串将映射到h3

中。

最新更新