Come and join us!
“The Newbies of Little Wo Shan” provides front-end developers with technical information and a series of basic articles. For a better user experience, please go to xhs-rookies.com/ to learn the latest articles.
“Code Tailor “, if you are interested in our article, or would like to make some suggestions, please follow the official account of “Rookie of Xiaohe Mountain” on wechat and contact us. You can also view our article on wechat. Every suggestion or approval is a great encouragement to us!
Actual combat case (three) : message function revision
We learned something new this time, and we need to change the previous version.
Added the “like” function
What if we need to like a comment?
This is fine if you control whether or not to display a like by passing in a property as you did last time.
We abstracted the InputCompoent input box component and the EvaluateCompoent list display component last time, but this time we need to add a comment component for the like function.
Remove unwanted components
Last time we abstracted the InputCompoent input box component and the EvaluateCompoent list display component into the Component folder, we first placed them directly in app.js. (For the sake of intuition, we will place these two abstractions directly in app.js.)
We simply abstracts a comment component and adds our like feature to the EvaluateCompoent list presentation component, which we can like for every comment in the list.
Therefore, we changed the home page app.js to the following:
import React, { PureComponent } from 'react'
import Comment from './comment'
import './App.css'
class App extends PureComponent {
constructor() {
super(a)this.state = {
title: 'Hello React'.desc: 'Did you know there was such a group? They have a dream, hard work, as a group of college students rookie, gave up the usual entertainment time, choose to learn together, grow together, the usual learning notes, summed up into the article, the purpose is very simple, I hope to help the rookie like them? Would you like to know more? Quick search wechat official account: newbies of Xiaohe Mountain, join them! '.comments: [{headPortrait: 'https://xhs-rookies.com/img/rookie-icon.png'.time: new Date(2021.4.14.21.2.30),
nickName: 'Rookie'.detail: 'This is a team that's coming up with a series of articles, so let's look forward to their work! '.liked: true.likeNum: 23],},text: ' ',}}render() {
const { title, desc, comments, text } = this.state
return (
<div className="App">
<h2>{title}</h2>
<div className="desc">{desc}</div>
<div style={{ width: '100'}} % >
<p className="commentsTitle">comments</p>
{comments.map((item, index) => {
return (
<Comment
key={item.time.getTime()}
changeLike={()= >{ this.changeLike(index) }} {... item} /> ) })}</div>
<div className="newComment">
<div style={{ display: 'flex' }}>
<img src="https://xhs-rookies.com/img/rookie-icon.png" className="" alt="" />
<textarea value={text} onChange={(e)= >This.changetext (e)} placeholder=" please input comments "/></div>
<div
className="submit"
onClick={()= >{this.addcomment ()}} > Publish</div>
</div>
</div>)}changeText(e) {
this.setState({ text: e.target.value })
}
changeLike(index) {
let newArray = [...this.state.comments]
letnewItem = { ... newArray[index] }if (newItem.liked) {
newItem.liked = false
newItem.likeNum -= 1
} else {
newItem.liked = true
newItem.likeNum += 1
}
newArray[index] = newItem
this.setState({
comments: newArray,
})
}
addComment() {
if (!this.state.text) {
alert('Please enter message content')
return
}
let detail = this.state.text
this.setState({ text: ' ' })
let newComment = {
headPortrait: 'https://xhs-rookies.com/img/rookie-icon.png'.time: new Date(),
nickName: 'Rookie',
detail,
liked: false.likeNum: 0,}this.setState({
comments: [newComment, ...this.state.comments],
})
}
}
App.propTypes = {}
export default App
Copy the code
Combine comment component
Thumb up function
First we need to consider what functionality this component needs.
Except for what I abstracted last time:
In addition to the profile picture, time, name and content, we also need a “like” button, which becomes red when clicked, and the number increases by one, and the color changes to gray again when clicked again, and the number decreases by one.
<span className={'likeBox ' + (liked ? 'like' : 'unlike')} onClick={() = > changeLike()}>
<span className="icon"> </span>
<span>{!!!!! likeNum && likeNum}</span>
</span>
Copy the code
One SPAN is used to store the like icon and one is used to display the number of likes.
Data detection
So this time we have a lot more data, and as more and more data is being passed to this component, how do we determine, or make sure that what’s coming in is correct? (Is it empty?)
PropType is used for content detection to quickly locate errors and fix them if they occur.
Comment.propTypes = {
nickName: PropTypes.string.isRequired,
time: PropTypes.object.isRequired,
headPortrait: PropTypes.string.isRequired,
detail: PropTypes.string.isRequired,
liked: PropTypes.bool.isRequired,
likeNum: PropTypes.number.isRequired,
changeLike: PropTypes.func.isRequired,
}
Copy the code
Eventually,
After adding the EvaluateCompoent to the EvaluateCompoent list display component with a “like” feature, our comment component is complete.
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import './comment.css'
class Comment extends PureComponent {
render() {
const { nickName, time, headPortrait, detail, liked, likeNum, changeLike } = this.props
return (
<div className="comment">
<div className="info">
<img src={headPortrait} alt="Avatar" />
<div>
<p className="nickname">{nickName}</p>
<p className="time">{this.getTime(time)}</p>
</div>
</div>
<div className="detail" style={{ marginBottom: '10px' }}>
{detail}
</div>
<div className="toolBox">
<span className={'likeBox'+ (liked ? 'like' : 'unlike')} onClick={()= > changeLike()}>
<span className="icon"> </span>
<span>{!!!!! likeNum && likeNum}</span>
</span>
<span className="share icon"> </span>
</div>
</div>)}getTime(time) {
const year = time.getFullYear()
const month = time.getMonth() + 1
const day = time.getDate()
const hour = String(time.getHours()).padStart(2.'0')
const minute = String(time.getMinutes()).padStart(2.'0')
const second = String(time.getSeconds()).padStart(2.'0')
return `${year}.${month}.${day} ${hour}:${minute}:${second}`
}
}
Comment.propTypes = {
nickName: PropTypes.string.isRequired,
time: PropTypes.object.isRequired,
headPortrait: PropTypes.string.isRequired,
detail: PropTypes.string.isRequired,
liked: PropTypes.bool.isRequired,
likeNum: PropTypes.number.isRequired,
changeLike: PropTypes.func.isRequired,
}
export default Comment
Copy the code
The source address
Github address of the project
Instant preview
We suggest using the form of Codesanbox to quickly access the current case online.
CodeSandBox
Next day forecast
In the next section, we’ll cover the basics of using State in React, delve deeper into the setState method, and more. Stay tuned!