[英]Loop through the array and return a `Dropdown.Item` element for each item
I am trying to loop through the todos array using the JavaScript map() function. 我试图使用JavaScript map()函数遍历todos数组。 I want to return a
Dropdown.Item
element for each item. 我想为每个项目返回一个
Dropdown.Item
元素。 When I click the Dropdown.Toggle
, an empty list expands. 当我单击
Dropdown.Toggle
,一个空列表会展开。 Dropdown.Item
and Dropdown.Toggle
are react bootstrap components. Dropdown.Item
和Dropdown.Toggle
是react引导程序组件。
Code here: https://stackblitz.com/edit/react-egxxcl 代码在这里: https : //stackblitz.com/edit/react-egxxcl
class App extends Component {
constructor() {
super();
this.state = {
todos: [{name: 'A', value: 10}, {name: 'B', value:20}]
};
}
render() {
return (
<div>
<Dropdown>
<Dropdown.Toggle variant="success" id="dropdown-basic">
Change
</Dropdown.Toggle>
<Dropdown.Menu >
{this.state.todos.map((todo, index) => {
<Dropdown.Item value={todo.value}>{todo.name}</Dropdown.Item>
})}
</Dropdown.Menu>
</Dropdown>
</div>
);
}
}
You don't return anything from the map
function, you can wrap it in parentheses or without to avoid using the return
keyword, also don't forget the key
prop. 您不会从
map
函数返回任何内容,可以将其包装在括号中,也可以避免使用return
关键字,也不要忘记key
道具。
I highly recommend using a linter to help you catch those small errors 我强烈建议您使用皮棉机来帮助您捕获那些小错误
You can also destructure value and name from the map callback function using ({})
您还可以使用
({})
从地图回调函数中解构值和名称。
({ propName })
<Dropdown.Menu>
{this.state.todos.map(({ name, value }) => (
<Dropdown.Item key={name} value={value}>{name}</Dropdown.Item>
))}
</Dropdown.Menu>
You just missed to return
from map
function. 您只是错过了从
map
功能return
。
{this.state.todos.map((todo, index) => {
return <Dropdown.Item value={todo.value}>{todo.name}</Dropdown.Item>
})}
or shorten, 或缩短
{this.state.todos.map((todo, index) => (
<Dropdown.Item value={todo.value}>{todo.name}</Dropdown.Item>
))}
or even shorten, 甚至缩短
{this.state.todos.map((todo, index) => <Dropdown.Item value={todo.value}>{todo.name}</Dropdown.Item>
)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.