我是刚刚接触react的小白白~
搭建项目
npm install -g create-react-app (全局安装react脚手架)
yarn create react-app my-app --template typescript
cd my-app
yarn start( 启动项目)
安装yarn 命令
npm install -g yarn
查看版本:yarn --version
在src文件夹下面建一个tsx文件 名为 ToDoList.tsx
import React,{useState,useEffect} from 'react'
interface IList{
id: number
name: string
age: string
}
function ToDoList(){
const [list,setList] = useState<IList[]>([])
const [name,setName] = useState('')
const [age,setAge] = useState('')
const [count,setCount] = useState(0)
const nameChnage = (e:any)=>{
setName(e.target.value)
}
const ageChange = (e:any)=>{
setAge(e.target.value)
}
const add = ()=>{
setCount(count+1)
if(age!==''&&name!==''){
list.push({id:count,name:name,age:age})
setAge('')
setName('')
}
console.log(count)
setList([...list])
}
const deleteData=(index:any)=>{
list.splice(index,1)
setList([...list])
}
return (
<div>
<h1>todolist</h1>
<div>
<span>name</span>
<input type="text" onChange={(e)=>nameChnage(e)} value={name}/>
</div>
<div>
<span>age</span>
<input type="text" onChange={(e)=>ageChange(e)} value={age}/>
</div>
<div>
<button onClick={()=>add()}>
新增
</button>
</div>
<table>
<tbody>
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
<th>edit</th>
</tr>
{/* <tr>
<td>0</td>
<td>one</td>
<td>1</td>
<td> <button>删除</button> </td>
</tr> */}
{
list.map((item,index)=>(
<tr key={index}>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.age}</td>
<td><button onClick={()=>deleteData(index)}>删除</button> </td>
</tr>
))
}
</tbody>
</table>
</div>
)
}
export default ToDoList
在app.tsx文件里面引入
import ToDoList from ‘./ToDoList’
(使用这个组件)
此列表可实现添加,删除功能