react-hooks 实现简单的评论list

react 16.7.0-alpha.2版本中推出了新版本的react-hook,详细的能够参照官方文档, 下面我讲用react-hooks实现简单的评论listjavascript

效果图:

demo总体架构使用react 16.8 + webpack + antd-mobilehtml

源代码:

  • 建立输入框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, 你们能够参考官方文档查看更多。java

相关文章
相关标签/搜索