react-hooks 实现简单的评论list

518 阅读1分钟

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('');
    
     <List style={{margin:'10px auto'}}>
        <InputItem value={value} placeholder="请输入详细信息" onChange={value => setValue(value)} /> 
      </List>
    
  • Button
     const publish = () => {
        setList(list.concat([{name:value}]));
        setValue('');
     }
    
     <Button type='primary' onClick={()=> publish()}>评论</Button>
    
  • list
     const removeTodo = index => {
        const todoList = [...list];
        todoList.splice(index,1);
        setList(todoList);
      }
     <ul>
        {list.map((item,index) => <li key={index}>{item.name} <span onClick={() => removeTodo(index)}>删除</span></li>)}
     </ul>

完整代码

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 (
    <div style={{margin: "0 30px"}}>
      <List style={{margin:'10px auto'}}>
        <InputItem value={value} placeholder="请输入详细信息" onChange={value => setValue(value)} /> 
      </List>
      <Button type='primary' onClick={()=> publish()}>评论</Button>
      <ul>
        {list.map((item,index) => <li key={index}>{item.name} <span onClick={() => removeTodo(index)}>删除</span></li>)}
      </ul>
    </div>
  )
}

这里只用了useState 和 useEffect 也是最常用的两个hook ,当然远远不止这两个hook, 大家可以参考官方文档查看更多。