React基础教程:TodoList案例

作者 : admin 本文共3132个字,预计阅读时间需要8分钟 发布时间: 2024-06-17 共1人阅读

todoList案例——增加

定义状态

// 定义状态
    state = {
        list: ["kevin", "book", "paul"]
    }

利用ul遍历list数组

<ul>
                    {
                        this.state.list.map(item =>
                            <li style={{fontWeight: "bold", fontSize: "20px"}} key={item.id}>{item.name}</li>
                        )
                    }
                </ul>

绑定点击事件,把input的值添加到list

不推荐这种写法❌

handlerClick = ()=>{
        console.log("Click4", this.myRef.current.value);

        // 不要这样写,因为不要直接修改状态,可能会造成不可预期的问题
        this.state.list.push(this.myRef.current.value);

        this.setState({
            list: this.state.list,
        })
    }

推荐这样的写法✅

handlerClick = ()=>{
        console.log("Click4", this.myRef.current.value);
    
    	// 定义一个新的数组接收
        let newList = [...this.state.list];
        newList.push(this.myRef.current.value);

        this.setState({
            list: newList
        })
    }

效果展示:

React基础教程:TodoList案例插图

这里会存在一个问题,如果我插入同样的key,比如paul,这里会提示报错,提示children存在相同的key,但是这个key应该是唯一的。

React基础教程:TodoList案例插图(1)

修改方式如下:

给list加入唯一标识id

// 定义状态
 state = {
     list: [
         {
             id: 1,
             name: "kevin"
         },
         {
             id: 2,
             name: "book"
         },
         {
             id: 3,
             name: "paul"
         }]
 }

ul进行遍历的时候,绑定唯一标识符item.id

<ul>
                    {
                        this.state.list.map(item =>
                            <li style={{fontWeight: "bold", fontSize: "20px"}} key={item.id}>{item.name}</li>
                        )
                    }
                </ul>

注意在push的时候也要添加id

newList.push({
         id: Math.random()*100000000, // 生产不同的id
         name: this.myRef.current.value
     });

再次添加相同的名字,也不会报错

React基础教程:TodoList案例插图(2)

todoList案例——删除

首先给每一个li标签后,添加删除按钮

<ul>
                    {
                        this.state.list.map(item =>
                            <li style={{fontWeight: "bold", fontSize: "20px"}} key={item.id}>{item.name}
                                <Button size={"small"}
                                        style={{marginLeft:10}}
                                        type={"primary"}
                                        shape={"circle"}
                                        danger
                                        icon={<DeleteOutlined/>} />
                            </li>
                        )
                    }
                </ul>

实现效果如下:

React基础教程:TodoList案例插图(3)

接着给按钮,绑定删除事件onClick={()=>this.handlerDeleteClick(index)},并且修改列表渲染的方式,(item,index),这里的index将作为后续的额参数传递使用

<ul>
                    {
                        this.state.list.map((item, index) =>
                            <li style={{fontWeight: "bold", fontSize: "20px"}} key={item.id}>{item.name}
                                <Button size={"small"}
                                        style={{marginLeft:10}}
                                        type={"primary"}
                                        shape={"circle"}
                                        danger
                                        onClick={()=>this.handlerDeleteClick(index)}
                                        icon={<DeleteOutlined/>} />
                            </li>
                        )
                    }
                </ul>

实现handlerDeleteClick函数

handlerDeleteClick(index) {
        console.log("Del-", index);
        // 深复制
        let newList = this.state.list.concat();
        newList.splice(index, 1);
        this.setState({
            list: newList
        })
    }

实现效果如下:

React基础教程:TodoList案例插图(4)

完整的代码

注意,这里我使用了react前端的UI框架antd,大家需要自行安装使用即可。

npm install antd --save
import React, {Component} from "react";
import {Button} from 'antd';
import {DeleteOutlined} from '@ant-design/icons';
import './css/App.css'
export default class App extends Component {
a = 35;
myRef = React.createRef();
// 定义状态
state = {
list: [
{
id: 1,
name: "kevin"
},
{
id: 2,
name: "book"
},
{
id: 3,
name: "paul"
}]
}
render() {
return (
<div style={{marginTop: 10, marginLeft: 10}}>
<input style={{width: 200}}
ref={this.myRef}/>
{/*非常推荐*/}
<Button style={{backgroundColor: '#2ba471', border: "none"}} size={"middle"} type={"primary"}
onClick={() => {
this.handlerClick() // 非常推荐,传参数
}}>添加</Button>
<ul>
{
this.state.list.map((item, index) =>
<li style={{fontWeight: "bold", fontSize: "20px"}} key={item.id}>{item.name}
<Button size={"small"}
style={{marginLeft: 10}}
type={"primary"}
shape={"circle"}
danger
onClick={() => this.handlerDeleteClick(index)}
icon={<DeleteOutlined/>}/>
</li>
)
}
</ul>
</div>
)
}
handlerClick = () => {
console.log("Click4", this.myRef.current.value);
// 不要这样写,因为不要直接修改状态,可能会造成不可预期的问题
// this.state.list.push(this.myRef.current.value);
let newList = [...this.state.list];
newList.push({
id: Math.random() * 100000000, // 生产不同的id
name: this.myRef.current.value
});
this.setState({
list: newList
})
}
handlerDeleteClick(index) {
console.log("Del-", index);
// 深复制
let newList = this.state.list.concat();
newList.splice(index, 1);
this.setState({
list: newList
})
}
}
本站无任何商业行为
个人在线分享 » React基础教程:TodoList案例
E-->