antdesign库的简单使用
实现如下的栗子:可以添加评论,进行评论的删除,观察到时间等

点击删除第二个之后

文件的路径如下所示

index.js文件
import React from 'react';
import ReactDOM from 'react-dom';
import 'moment/locale/zh-hk';
import 'antd/dist/antd.css';
import App from './comment/App';
ReactDOM.render(
<App />,
document.getElementById('root')
);
app.js
import React, { PureComponent } from 'react';
import CommentInput from './components/CommentInput';
import CommentItem from './components/CommentItem';
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}
removeItem={e => this.removeComment(index)}/>
})
}
<CommentInput submitComment={this.submitComment.bind(this)}/>
</div>
)
}
//添加评论
submitComment(info) {
this.setState({
commentList: [...this.state.commentList, info]//浅拷贝之后的新数组
})
}
//删除评论
removeComment(index) {
const newCommentList = [...this.state.commentList];
newCommentList.splice(index, 1);
this.setState({
commentList: newCommentList
})
}
}
CommentInput.js
使用了输入和按钮的组件
- Input
- Button
还有日期处理类库moment
import React, { PureComponent } from 'react';
import moment from 'moment';
import { Input, Button } from "antd";
export default class CommentInput extends PureComponent {
constructor(props) {
super(props);
this.state = {
content: ""
}
}
render() {
return (
<div>
<Input.TextArea rows={4}
value={this.state.content}
onChange={e => this.handleChange(e)}/>
<Button type="primary" onClick={e => this.addComment()}>添加评论</Button>
</div>
)
}
handleChange(event) {
this.setState({
content: event.target.value
})
}
//添加评论中的属性
addComment() {
const commentInfo = {
id: moment().valueOf(),
avatar: "https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png?imageMogr2/auto-orient/strip|imageView2/1/w/240/h/240",
nickname: "gercke",
datetime: moment(),
content: this.state.content,
comments: [
]
}
//清空评论狂中的东西
this.props.submitComment(commentInfo);
this.setState({
content: ""
})
}
}
CommentItem.js
用到了一些组件
- Comment, //评论组件
- Avatar, //头像组件
- Tooltip //显示时间组件
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;//es6扩展
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.removeItem()}><DeleteOutlined />删除</span>
]}
/>
)
}
removeItem() {
this.props.removeItem();
}
}
本文介绍了如何利用antdesign库创建一个简单的评论功能,包括添加、删除评论以及时间展示。涉及组件有Input、Button和Moment库,以及Comment、Avatar和Tooltip。
1244

被折叠的 条评论
为什么被折叠?



