reactjs - 在 React 中显示项目列表
问题描述
我有一个简单的购物清单组件来显示状态中的项目
如何使用 ul 列表执行此操作
这是我的代码
我在 items.map 周围遇到错误,它说它期待一个:
import React, {Component} from 'react'
import uuid from 'uuid';
class ShoppingList extends Component {
state = {
items:[
{id: uuid(), name: 'Eggs'},
{id: uuid(), name: 'Bacon'},
{id: uuid(), name: 'Beans'},
{id: uuid(), name: 'Black Pudding'}
]
}
render(){
const {items} = this.state;
return(
<button
onClick={() =>{
const name = prompt('Enter Item');
if(name){
this.setState(state => ({
items: [...state.items, {id: uuid(), name}]
}));
}
}}
>
Add Item
</button>
<ul>
{items.map(({id,name}) => (
<li key={id}>
{name}
</li>
))}
</ul>
)
}
}
export default ShoppingList
解决方案
你只需要一个顶级 JSX 元素。请参阅我添加的额外 div。
编辑
我想指出@cr05s19xx 关于提取 onClick 处理程序的答案。使用这种逻辑是一种很好的行为。此外,如果额外div
破坏了一些 CSS,那么您可以React.Fragment
按照 @cr05s19xx 的建议再次使用。所以,另一个答案可能比我的更好:)
class ShoppingList extends React.Component {
state = {
items: [
{ id: 1, name: "Eggs" },
{ id: 2, name: "Bacon" },
{ id: 3, name: "Beans" },
{ id: 4, name: "Black Pudding" }
]
};
render() {
const { items } = this.state;
return (
<div>
<button
onClick={() => {
const name = prompt("Enter Item");
if (name) {
this.setState(state => ({
items: [...state.items, { id: uuid(), name }]
}));
}
}}
>
Add Item
</button>
<ul>
{items.map(({ id, name }) => (
<li key={id}>{name}</li>
))}
</ul>
</div>
);
}
}
ReactDOM.render(
<ShoppingList />,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root" />
推荐阅读
- javascript - 如何在 Web Worker 中访问客户端 URL?
- javascript - 遍历文件夹中的文件(javascript)
- python - Python - 输入()产生“无”
- r - 如何将我的 cox.zph(cpfit.sd) 输出作为 csv 文件而不是仅在控制台中
- oracle - Oracle中是否继承了主键、唯一键、外键等约束?
- azure - Azure 人脸验证 API 和 Azure Demo 的人脸匹配率不同
- spring-webflux - 直接从 Spring Gateway 发送来自预过滤器的错误响应
- react-native - 世博推送通知服务
- java - 在java中保留上周的子字符串日期从当天开始?
- javascript - 如何在不手动重建的情况下复制和渲染 React 元素?