join us!
161134b4ec3bd5 " , to provide front-end developers with technical information and a series of basic articles. For a better user experience, please move to our official website novices (161134b4ec3bda https://xhs-rookies.com/ ) to learn and get the latest articles in time.
"Code Tailor" , if you are interested in our articles, or would like some advice, micro-channel attention "Xiaoheshan newbies" public number, contact us take, you can also watch it on the micro-letter Our article. Every suggestion or approval is a great encouragement to us!
Practical case: message function
We have finished learning some basic content of react-hooks, and now is our actual combat link.
The function of the project is similar to the content of our React tutorial. For details, please refer to, React Series-Practical Case: Add login
Effect
The actual combat we have to do is very simple, it is a simple message function.
renderings:
Login page
Login status maintenance
If we log in successfully, we should need a place to store information, in preparation for subsequent authentication, we use localStorage
for data persistence processing.
this.props.history.replace('/home')
window.localStorage.islogin = '1'
Go to the homepage for authentication
We need to authenticate on the login page. We let the login
page judge when the loading is complete. If you have already logged in, then we will jump to the home
homepage. To achieve this effect, we need to be in useEffect()
, before the page is displayed Make judgments.
useEffect(() => {
let localStorage = window.localStorage
if (localStorage.islogin === '1') {
props.history.replace('/home')
}
})
All codes of the login page
Use two useState()
to record the account password entered by the user, and then use it for login verification.
import React, { useEffect, useState } from 'react'
import './login.css'
function Login(props) {
useEffect(() => {
let localStorage = window.localStorage
if (localStorage.islogin === '1') {
props.history.replace('/home')
}
})
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
return (
<div className="login">
<h2>欢迎来到XXX博客区</h2>
<form className="form">
<div className="formItem">
<label htmlFor="username">用户名:</label>
<input
type="text"
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div className="formItem">
<label htmlFor="password">密码:</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div className="loginBtn" onClick={() => handleLogin()}>
登录
</div>
</form>
</div>
)
function handleLogin() {
if (username && password) {
props.history.replace('/home')
window.localStorage.islogin = '1'
alert('欢迎!')
} else {
alert('请输入用户名和密码!')
}
}
}
export default Login
Home page
import React, { useState } from 'react'
import Comment from './comment'
import checkRole from './checkRole'
import './App.css'
function App(props) {
const [title, setTitle] = useState('Hello Hooks')
const [desc, setDesc] = useState(
'你知道有这么一个团队吗?他们怀揣梦想,艰苦奋斗,作为一群大学生菜鸟,放弃了平时娱乐的时间,选择一起学习,一起成长,将平时学习的笔记,心得总结为文章,目的很简单,希望可以帮助向他们一样的菜鸟们?你想了解更多吗?快搜索微信公众号:小和山的菜鸟们,加入他们吧!',
)
const [comments, setComments] = useState([
{
headPortrait: 'https://xhs-rookies.com/img/rookie-icon.png',
time: new Date(2021, 4, 14, 21, 2, 30),
nickName: '小菜鸟',
detail: '这是一个即将推出系列文章的团队,我们一起期待他们的作品吧!',
liked: true,
likeNum: 23,
},
])
const [text, setText] = useState('')
return (
<div className="App">
<span className="logout" onClick={handleLogout}>
退出登录
</span>
<h2>{title}</h2>
<div className="desc">{desc}</div>
<div style={{ width: '100%' }}>
<p className="commentsTitle">评论</p>
{comments.map((item, index) => {
return (
<Comment key={item.time.getTime()} changeLike={() => 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={changeText} placeholder="请输入评论" />
</div>
<div className="submit" onClick={addComment}>
发表
</div>
</div>
</div>
)
// 退出登录
function handleLogout() {
window.localStorage.islogin = '0'
props.history.replace('/login')
}
// 改变text
function changeText(e) {
setText(e.target.value)
}
function changeLike(index) {
let newArray = [...comments]
let newItem = { ...newArray[index] }
if (newItem.liked) {
newItem.liked = false
newItem.likeNum -= 1
} else {
newItem.liked = true
newItem.likeNum += 1
}
newArray[index] = newItem
setComments(newArray)
}
function addComment() {
if (!text) {
alert('请输入留言内容')
return
}
let detail = text
setText('')
let newComment = {
headPortrait: 'https://xhs-rookies.com/img/rookie-icon.png',
time: new Date(),
nickName: '小菜鸟',
detail,
liked: false,
likeNum: 0,
}
setComments([newComment, ...comments])
}
}
export default App
Components used
comment component
This component is used to display user messages, displayed by data.
import React from 'react'
import './comment.css'
function Comment(props) {
const { nickName, time, headPortrait, detail, liked, likeNum, changeLike } = props
return (
<div className="comment">
<div className="info">
<img src={headPortrait} alt="头像" />
<div>
<p className="nickname">{nickName}</p>
<p className="time">{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>
)
function 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}`
}
}
export default Comment
Summarize
At this point, our hooks
actual combat is over. Although it is just a simple message function, it also contains some usage of hooks.
If you need to view the source code, you can view and download our open source library project github address
Preview of the next section
hooks
has come to an end. Next, in this golden, ninety and silver tenth time period, we will bring you wonderful interview questions, so stay tuned!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。