react——antdesign使用案例:添加评论,删除评论

tech2022-07-05  164

App.js:

import React, { PureComponent } from 'react' import Commentitem from './components/Commentitem.js' import Commentinput from './components/Commentinput.js' export default class App extends PureComponent { constructor(props){ super(props); this.state={ commentlist:[] } } render() { return ( <div style={{width:"500px",padding:"20px"}}> { this.state.commentlist.map((item,index)=>{ return <Commentitem key={item.id} comment={item} removeComment={e=>this.remove(index)}/> }) } <Commentinput submit={this.submit.bind(this)}/> </div> ) } submit(info){ this.setState({ commentlist: [...this.state.commentlist,info] }) } remove(index){ const newCommentlist=[...this.state.commentlist] newCommentlist.splice(index,1) this.setState({ commentlist:newCommentlist }) } }

两个组件代码:

import React, { PureComponent } from 'react' import {Comment,Avatar,Tooltip} from 'antd' import {DeleteOutlined} from '@ant-design/icons' export default class Commentitem extends PureComponent { render() { const {nickname,avatar,content,datetime}=this.props.comment; return ( <Comment author={<a href="/#">{nickname}</a>} avatar={<Avatar src={avatar} alt={nickname}/>} content={<p>{content}</p>} datetime={ <Tooltip title={datetime.format("YYYY-MM-DD")}> <span>{datetime.fromNow()}</span> </Tooltip> } actions={[ <span onClick={e=>this.removeComment()}><DeleteOutlined />删除</span> ]} /> ) } removeComment(){ this.props.removeComment() } } import React, { PureComponent } from 'react' import { Input,Button } from 'antd' import moment from 'moment' export default class Commentinput extends PureComponent { constructor(props){ super(props); this.state={ content:"" } } render() { return ( <div> <Input.TextArea rows={5} value={this.state.content} onChange={e=>this.handlechange(e)}/> <Button type="primary" style={{marginTop:"10px"}} onClick={e=>this.addcomment()}>添加评论</Button> </div> ) } handlechange(event){ this.setState({ content:event.target.value }) } addcomment(){ const commentInfo={ id:moment().valueOf(), avatar:"https://tvax3.sinaimg.cn/crop.0.0.512.512.1024/83157fd3ly8fw432kq7u8j20e80e8js3.jpg?KID=imgbed,tva&Expires=1599044684&ssig=99V28dDv6g", nickname:"kk", datetime:moment(), content:this.state.content } this.props.submit(commentInfo); this.setState({ content:"" }) } }

写的过程中报了一个错误:Uncaught TypeError: this.state is null

原因是 state拼写错了!!!

 

最新回复(0)