react-hooks 实现简单的评论list

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, 大家可以参考官方文档查看更多。

转载于:https://juejin.im/post/5c8670c2e51d45206776888b

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值