react 16.7.0-alpha.2版本中推出了新版本的react-hook,详细的可以参照, 下面我讲用react-hooks实现简单的评论list
效果图:
demo整体架构使用react 16.8 + webpack + antd-mobile
源代码:
- 创建输入框hooks
const [list, setList] = useState([{ name: 'mark'}, { name: 'joan'}]); const [value, setValue] = useState('');
setValue(value)} /> - Button
const publish = () => { setList(list.concat([{name:value}])); setValue(''); } 复制代码
- list
const removeTodo = index => { const todoList = [...list]; todoList.splice(index,1); setList(todoList); }
- {list.map((item,index) =>
- {item.name} removeTodo(index)}>删除 )}
完整代码
import React, { useState, useEffect} from 'react';import {Button, InputItem, List} from 'antd-mobile';const Home = () => { const [list, setList] = useState([{ name: 'mark'}, { name: 'joan'}]); const [value, setValue] = useState(''); const removeTodo = index => { const todoList = [...list]; todoList.splice(index,1); setList(todoList); } const publish = () => { setList(list.concat([{ name:value}])); setValue(''); } useEffect(()=>{ console.log('list变化了'); }, [list]) return ()}复制代码
setValue(value)} /> {list.map((item,index) =>
- {item.name} removeTodo(index)}>删除
)}
这里只用了useState 和 useEffect 也是最常用的两个hook ,当然远远不止这两个hook, 大家可以参考官方文档查看更多。