我有这段返回组件的代码:
const Test = ({places}) => (
<div>
{places.map(place => (
<div className="location" key={place.slug}>
<div className="photo" style={ { backgroundImage: "url(" + place.src + ")" } }></div>
<h2>{place.name}</h2>
</div>
))}
</div>
);
但我对 (
感到困惑和 {
括号。我实际上是在尝试摆脱外部 <div>
标签,但当我使用时它似乎不起作用:
const Test = ({places}) => (
{places.map(place => (
<div className="location" key={place.slug}>
<div className="photo" style={ { backgroundImage: "url(" + place.src + ")" } }></div>
<h2>{place.name}</h2>
</div>
))}
);
最佳答案
您需要使用那个 div
,原因是您正在使用 map
动态创建元素和 map
将返回一个数组,我们不能返回多个元素,因此您需要将它们包装在一个 div 中。
一个 React
组件不能返回多个元素,但是一个 JSX 表达式可以有多个子元素,所以如果你想让一个组件渲染多个东西,你可以将它包装在一个 div 中
。
不要忘记它是一个函数式组件,函数总是接受多个参数并总是只返回一个值。
更新:
如果你想做一些计算或者想在函数式组件中定义变量,那么可以这样写组件:
const Test = ({places}) => { //use {
let a = 1, b = [1,2,3,4];
b.forEach(el => console.log(el));
return( //use return to return the html elements
<div>
hello world!!!
//other elements
......
</div>
)
};
关于javascript - 在 React 中使用 map 创建组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43856159/