前提是假定已经搭建好了react环境,antd的ui框架,首先我们来先看下效果

在vue中实现这个功能想必大家都没问题了,那么在react中如何实现呢?
需要注意的几个地方:
1.react没有自带计算属性的概念,要实现类似在vue的computed功能,需要自己开发
2.react没有vue的动态设置属性的概念,类似于vue的Object,Array的$set是不存在的
3.react没有自带的响应式概念,要实现类似vue的双向绑定需要手动实现
话不多说,上代码
核心组件
import TodoComponents from "./components/TodoComponents";
import "./App.css";
function App() {
return (
<div>
<TodoComponents></TodoComponents>
</div>
);
}
export default App;
@import "~antd/dist/antd.css";
.App,
.wrap {
height: 100%;
position: relative;
}
.nav-lists {
display: flex;
height: 80px;
background: #000;
color: #fff;
line-height: 80px;
justify-content: space-between;
}
nav {
position: absolute;
bottom: 0;
left: 0;
right: 0;
}
nav ul li {
margin: 0 6px;
}
//TodoComponents.js文件
import React, { Component } from "react";
import "./Todo.css";
import { Button, Input, List, Checkbox, Radio } from "antd";
class TodoComponents extends Component {
state = {
list: [],
title: "",
radioValue: "a",
};
addItemToLists = () => {
this.setState({
list: [
...this.state.list,
{
title: this.state.title,
isSelect: false,
},
],
title: "",
});
};
changeValue = (key, e) => {
//es6的动态属性特性
this.setState({
[key]: e.target.value,
});
};
deleteItem = (index) => {
//复制一份list然后进行处理,再重新赋值
let list = this.state.list;
list.splice(index, 1);
this.setState({
list: list,
});
};
changeChecked = (index) => {
//复制一份list然后进行处理,再重新赋值
let list = this.state.list;
list[index].isSelect = !list[index].isSelect;
this.setState({
list,
nowIndex: index,
});
};
render() {
const { list, title, isSelect, nowIndex, radioValue } = this.state;
//这里获取数据的实时更新
//计算总数
const totalSum = list.length;
//计算已完成
const hasFinished = list.filter((item) => item.isSelect).length;
//计算未完成
const noFinished = list.filter((item) => !item.isSelect).length;
return (
<div className="content">
<Input
value={title}
allowClear
onPressEnter={this.addItemToLists}
onChange={(e) => this.changeValue("title", e)}
style={{ width: "200px" }}
/>
<Button onClick={this.addItemToLists} type="primary">
确定
</Button>
<div style={{ width: "258px" }}>
<List
dataSource={list}
bordered
renderItem={(item, index) => {
return (
<div>
<List.Item>
<Checkbox
defaultChecked={item.isSelect}
onChange={() => this.changeChecked(index)}
/>
<span className={item.isSelect ? "isChecked" : ""}>
{item.title}
</span>
<Button onClick={() => this.deleteItem(index)}>删除</Button>
</List.Item>
</div>
);
}}
/>
</div>
<div>
<Radio.Group
value={radioValue}
size="large"
>
<Radio.Button value="a">
<span>全部:{totalSum}</span>
</Radio.Button>
<Radio.Button value="b">
<span>已完成:{hasFinished}</span>
</Radio.Button>
<Radio.Button value="c">
<span>未完成:{noFinished}</span>
</Radio.Button>
</Radio.Group>
</div>
</div>
);
}
}
export default TodoComponents;
总结
整个过程比较简单,思维方式与vue有点不同,所以我们需要跳出vue的思维习惯去开发
729

被折叠的 条评论
为什么被折叠?



