react使用函数组件创建todolist

1、安装

create-react-app todoListNew

npm install antd --save

目录结构
src
-compoent
--Home.js
--List.js
App.js

2、App.js

import React from 'react';
import Home from './component/Home'
function App() {
  return (
    <div className="App">
    <Home/>
    </div>
  );
}

export default App;

2、Home.js

import React, {useState} from 'react'
import List from './List'
import { Input, Button, Row, Col } from 'antd';

function Home() {
  const [inputVal, setInputVal] = useState('')
  const [todoList, setTodoList] = useState([]) 

  const handleAdd = () => {
    if (!inputVal) return
    setTodoList([...todoList, inputVal])
    setInputVal('')
  }

  const hanleDel = (i) => {
    let list = todoList
    list.splice(i, 1)
    setTodoList([...list])
  }

  return (
    <>
      <Row>
        <Col span={12}>
          <Input placeholder="输入值" value={inputVal} onChange={(e) => setInputVal(e.target.value)} />
        </Col>
        <Col span={12}>
          <Button type="primary" onClick={handleAdd}>添加</Button>
        </Col>
      </Row>
      <List todoList={todoList} hanleDel={hanleDel}/>
    </>
  )
}
export default Home;

3、List.js

import React, { useEffect } from 'react'
import { Button, Row, Col } from 'antd';
function List(props) {
  const {todoList, hanleDel} = props
  useEffect(() => {
    console.log('挂载了。。。');
  }, [])

  return (
    <ul>
      {
        todoList.map((item, i) => {
          return <li key={i} style={{'marginBottom':'10px'}}>
            <Row>
              <Col>
                {item}
              </Col>
              <Col>
                <Button type="primary" onClick={() => hanleDel(i)}>删除</Button>
              </Col>
              {/* <Col>
                
              </Col> */}
            </Row>
          </li>
        })
      }
    </ul>
  )
}
export default List;

 

原文地址:https://www.cnblogs.com/-roc/p/14500195.html