一、后端
package com.example.readinglist.cms.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.readinglist.cms.dao.NoteMapper;
import com.example.readinglist.cms.dto.ResponseDTO;
import com.example.readinglist.cms.entity.Note;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Date;
/**
* <p>
* 前端控制器
* </p>
*
* @author *cruder
* @since 2021-03-31
*/
@RestController
@RequestMapping("/note")
public class NoteController {
@Resource
NoteMapper noteMapper;
@GetMapping("/findList")
public ResponseDTO findList(@RequestParam("userId") String userId,String keyword){
return ResponseDTO.success(noteMapper.selectList(new QueryWrapper<Note>().
eq("user_id",userId).like(StringUtils.isNotEmpty(keyword),"content",keyword)
.orderByDesc("note_time")));
}
@PostMapping("/saveOrupdate")
public ResponseDTO saveOrupdate(@RequestBody Note note){
note.setNoteTime(new Date());
if(note.getNoteId()!=null){
noteMapper.updateById(note);
}else {
noteMapper.insert(note);
}
return ResponseDTO.success();
}
@GetMapping("/delete")
public ResponseDTO delete(@RequestParam("noteId") Integer noteId){
return ResponseDTO.success(noteMapper.deleteById(noteId));
}
@GetMapping("/deleteAll")
public ResponseDTO deleteAll(@RequestParam("userId") String userId){
return ResponseDTO.success(noteMapper.delete(new QueryWrapper<Note>().eq("user_id",userId)));
}
}
二、前端
1)入口文件
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {Switch,Route,HashRouter} from 'react-router-dom';
import NoteList from './page/page01/NoteList'
import Note from './page/page02/Note'
import Home from './page/index/Home'
const vDom = <div id="demo">Hello,React!</div>
ReactDOM.render(
<HashRouter>
<Switch>
<Route path='/note' component={Note}/>
<Route path='/noteList' component={NoteList}/>
<Route component={Home}/>
</Switch>
</HashRouter>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
这个是create-react-app 命令执行之后自动生成的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
2)第一个页面
import React from 'react'
import axios from 'axios'
import './notelist.css'
import {Modal,SearchBar} from 'antd-mobile'
import 'antd-mobile/dist/antd-mobile.css'
const alert = Modal.alert;
var flag = 0;
class NoteList extends React.Component{
constructor(props){
super(props);
this.state=({noteList:[]})
}
componentDidMount(){
axios.get('/note/findList?userId=user121').then(res=>{
this.setState({noteList:res.data.data});
}).catch((err)=>{console.log(err)})
}
showAlert = (item) => {
const alertInstance = alert('Delete', 'Are you sure???', [
{ text: 'Cancel', onPress: () => console.log('cancel'), style: 'default' },
{ text: 'OK', onPress: () => {console.log('ok',item);axios.get('/note/delete?noteId='+item.noteId)
.then(res=>{
if(res.data===200){
alert('删除成功!');
//这里要重新加载页面
}
})} },
]);
setTimeout(() => {
// 可以调用close方法以在外部close
console.log('auto close');
alertInstance.close();
}, 500000);
};
static toNote(item){
console.log("响应点击事件",item);
localStorage.setItem('note',null);
window.location.href="#/note";
}
myVar;
_touchStart = (item) => {
// 设置定时器
this.myVar = setInterval(function () {
flag ++;
}
, 500);
}
_touchEnd = (item) => {
// 这里执行点击的操作,长按和 点击互不影响
if (flag>=1) {
console.log('长安',item);
this.showAlert(item)
}else {
this.onClick(item)
}
flag = 0;
clearInterval(this.myVar)
}
onClick = (item) => {
console.log('点击',item);
// window.location.href="#/note?noteId="+item.noteId+"&content="+item.content;
window.location.href="#/note";
localStorage.setItem('note',JSON.stringify(item))
}
search(e){
axios.get('/note/findList?userId=user121&keyword='+e).then(res=>{
//为什么有设置不进去了?
this.setState({noteList:res.data.data});
console.log(res.data.data,this.state.noteList);
}).catch((err)=>{console.log(err)})
}
deleteAll(){
axios.get('/note/deleteAll?userId=user121').then(res=>{
alert('删除成功!');
}).catch((err)=>{console.log(err)});
window.location.href='#/noteList';
}
render(){
return <div>
<div className="outDiv">
<SearchBar className="search" onSubmit={this.search.bind(this)}/>
<div>
{this.state.noteList.map(item=>(<div className="li" key={item.noteId}
onTouchStart={this._touchStart.bind(this,item)} onTouchEnd={this._touchEnd.bind(this,item)}>
<div className="note_title">{item.content.substring(0,15)+'...'}</div>
<div className="note_time">{item.noteTime}</div>
</div>))}
<button className="btn_add" onClick={NoteList.toNote}>添加</button>
{this.state.noteList.length===0?null:<button className="btn_delete" onClick={this.deleteAll}>删除</button>}
</div>
</div>
</div>
}
}
export default NoteList
.search{
margin-top: 20px;
}
.outDiv{
margin-left: auto;
margin-right: auto;
width: 80%;
background-color: gray();
}
.li{
height:60px;
border-style: solid;
border-width: 1px;
border-color: blueviolet;
margin-top: 15px;
border-radius: 15px;
}
.note_title{
margin-top: 5px;
margin-left: 5px;
font-weight: bolder;
font-size: large;
}
.note_time{
margin-top: 5px;
margin-left: 5px;
}
.btn_add{
position: absolute;
top: 580px;
right: 30px;
width: 50px;
height: 50px;
color: white;
background-color: #61dafb;
border-radius: 50%;
}
.btn_delete{
position: absolute;
top: 650px;
right: 30px;
width: 50px;
height: 50px;
color: white;
background-color: red;
border-radius: 50%;
}
3)第二个页面
import React from 'react'
import axios from 'axios'
import './note.css'
class Note extends React.Component{
constructor(props){
super(props);
this.handleChange = this.handleChange.bind(this);
this.state=({noteId:'',content:''})
}
handleChange(e){
console.log("监听到文本变化,",e.target.value);
this.setState({content: e.target.value});
}
back(){
window.location.href="#/noteList";
}
save(){
const note = {
content:this.state.content,
userId:'user121',
noteId:this.state.noteId
};
axios.post('/note/saveOrupdate',note).then(res=>{
if(res.data.code===200){
alert('保存成功!');
}else {
alert('保存失败!');
}
}).catch((err)=>{console.log(err);})
}
componentDidMount(){
// const param = this.props.location.search;
// const params = param.split('&')
// this.setState({noteId:params[0].split('=')[1],
// content:params[1].split('=')[1]});
let note = localStorage.getItem('note');
if(note!=='null'){
note = JSON.parse(note);
this.setState({noteId:note.noteId,content:note.content})
}
}
render(){
return <div>
<textarea className="text" onChange={this.handleChange} defaultValue={this.state.content}/>
<div><button className="btn_back" onClick={this.back}>返回</button>
<button className="btn_save" onClick={this.save.bind(this)} >保存</button></div>
</div>
}
}
export default Note
.text{
width:90%;
margin-top: 30px;
margin-left: 18px;
margin-right: 20px;
height: 650px;
line-height: 2em;
border-color: green;
}
.btn_back{
background-color: deepskyblue;
border-radius: 10px;
width: 50px;
height: 30px;
margin-left: 60px;
}
.btn_save{
background-color: mediumspringgreen;
border-radius: 10px;
width: 50px;
height: 30px;
margin-left: 160px;
}
长按删除笔记,点击进入笔记。