首页 > 技术文章 > 八、8.2自写模块,引入及使用(封装)

chenxi188 2019-11-12 17:01 原文

上接:https://blog.csdn.net/u010132177/article/details/103022377

自定义模块及使用(封装)

1.上节代码:【todolistOk.js】

其中的localStorage函数部分明显在使用中比较麻烦,我们将对其进行提取,单独封闭成一个模块

import React, { Component } from 'react';
import { stringify } from 'querystring';

class TodoList extends Component {
    constructor(props){
        super(props);
        
        this.state={
          msg:'todolist:',
          list:[
           /* {title:'录制ionic',checked:true},
            {title:'录制nodejs',checked:false},
            {title:'录制egg.js',checked:true},
            {title:'录制vue',checked:false}
           */
            ]
        }
    }

    //0.把input值添加到state的list里
    addList=(e)=>{
        if(e.keyCode==13){ //如果按下的是回车键则执行以下代码
            let tempList=this.state.list; //获取state的默认列表为临时列表
            let title=e.target.value; //把input输入的值赋值给临时title,此处也可用ref来传值:this.ref.ref_value.value
            tempList.push({title:title,checked:false}) //把临时title推到templist临时列表时,checked默认为false
            this.setState({ //把临时列表正式加入的state的列表
                list:tempList
            });
            e.target.value=''; //添加成功后清除input为空
            localStorage.setItem('todolist',JSON.stringify(tempList)); //把表转化为string转化为字符串存入名为todolist的列表
        }
    }

    //1. checkbox处理函数注意传过来的key值源自.bind(this,key)
    handleCheck=(key)=>{
        let tempList=this.state.list;
        tempList[key].checked=!tempList[key].checked; //把对应的表的checked的值取反,即:是false变true,是true变false; 
        this.setState({
            list:tempList
        })
        localStorage.setItem('todolist',JSON.stringify(tempList)); //把表转化为string转化为字符串存入名为todolist的列表
    }

    //2. 删除事项函数
    dellist=(key)=>{
        let tempList=this.state.list;
        tempList.splice(key,1)
        this.setState({
            list:tempList
        })
        localStorage.setItem('todolist',JSON.stringify(tempList)); //把表转化为string转化为字符串存入名为todolist的列表
    }

    //3.生命周期函数componentDidMount()  页面加载就会触发
    componentDidMount(){
        var todolist=JSON.parse(localStorage.getItem('todolist'));   //json.parse转化成对象(获取缓存的数据- 字符串格式)
        if(todolist){
            this.setState({
                list:todolist
            })
        }
     }

    render() {
      return (
        <div>
        {this.state.msg}<input onKeyUp={this.addList} /><br/>
        <hr/>
        <h2>待办事项:</h2>
        <ul>{
            this.state.list.map((value,key)=>{
                if(value.checked==false){ 
                    return( 
                    <li key={key}>
                        <input type='checkbox' checked={value.checked} onChange={this.handleCheck.bind(this,key)} /> 
                        {value.title}--
                        <button onClick={this.dellist.bind(this,key)}>删除</button>
                    </li>
                    )
                }
            })
            }</ul><br/>

        <hr/>
        <h2>已完成事项:</h2>
        <ul>{
            this.state.list.map((value,key)=>{
                if(value.checked==true){
                    return( 
                    <li key={key}>
                        <input type='checkbox' checked={value.checked} onChange={this.handleCheck.bind(this,key)} />
                        {value.title}--
                        <button onClick={this.dellist.bind(this,key)}>删除</button>
                    </li>
                    )
                }
            })
            }</ul><br/>
        </div>
      );
    }
}
export default TodoList;

2.封装

重点:【自定义封装类:storage.js】

var storage={ //类名
    set(key,value){
        localStorage.setItem(key,JSON.stringify(value)); //设置storage,把传进来的参数二转为字符串,key就是key
    },
    get(key){
        return JSON.parse(localStorage.getItem(key)); //获取名为key的storge值,把值转为对象(字典),并返回
    },
    remove(key){
        localStorage.removeItem(key); //删除名为key的storage的值。
    }
}
export default storage; //暴露出类名 其它地方引用:

【todolistClass.js】

import React, { Component } from 'react';
import { stringify } from 'querystring';
import storage from './model/storage.js'; //引入自定义类

class TodoList extends Component {
    constructor(props){
        super(props);
        
        this.state={
          msg:'todolist:',
          list:[
            {title:'录制ionic',checked:true},
            {title:'录制nodejs',checked:false},
            {title:'录制egg.js',checked:true},
            {title:'录制vue',checked:false}
            ]
        }
    }

    //0.把input值添加到state的list里
    addList=(e)=>{
        if(e.keyCode==13){ //如果按下的是回车键则执行以下代码
            let tempList=this.state.list; //获取state的默认列表为临时列表
            let title=e.target.value; //把input输入的值赋值给临时title,此处也可用ref来传值:this.ref.ref_value.value
            tempList.push({title:title,checked:false}) //把临时title推到templist临时列表时,checked默认为false
            this.setState({ //把临时列表正式加入的state的列表
                list:tempList
            });
            e.target.value=''; //添加成功后清除input为空
            storage.set('todolist',tempList); //用自定义的storage类,把表转化为string转化为字符串存入名为todolist的列表
        }
    }

    //1. checkbox处理函数注意传过来的key值源自.bind(this,key)
    handleCheck=(key)=>{
        let tempList=this.state.list;
        tempList[key].checked=!tempList[key].checked; //把对应的表的checked的值取反,即:是false变true,是true变false; 
        this.setState({
            list:tempList
        })
        storage.set('todolist',tempList); //用自定义的storage类,把表转化为string转化为字符串存入名为todolist的列表
    }

    //2. 删除事项函数
    dellist=(key)=>{
        let tempList=this.state.list;
        tempList.splice(key,1)
        this.setState({
            list:tempList
        })
        storage.set('todolist',tempList); //把表转化为string转化为字符串存入名为todolist的列表
    }

    //3.生命周期函数componentDidMount()  页面加载就会触发
    componentDidMount(){
        var todolist=JSON.parse(localStorage.getItem('todolist'));   //json.parse转化成对象(获取缓存的数据- 字符串格式)
        if(todolist){
            this.setState({
                list:todolist
            })
        }
     }

    render() {
      return (
        <div>
        {this.state.msg}<input onKeyUp={this.addList} /><br/>
        <hr/>
        <h2>待办事项:</h2>
        <ul>{
            this.state.list.map((value,key)=>{
                if(value.checked==false){ 
                    return( 
                    <li key={key}>
                        <input type='checkbox' checked={value.checked} onChange={this.handleCheck.bind(this,key)} /> 
                        {value.title}--
                        <button onClick={this.dellist.bind(this,key)}>删除</button>
                    </li>
                    )
                }
            })
            }</ul><br/>

        <hr/>
        <h2>已完成事项:</h2>
        <ul>{
            this.state.list.map((value,key)=>{
                if(value.checked==true){
                    return( 
                    <li key={key}>
                        <input type='checkbox' checked={value.checked} onChange={this.handleCheck.bind(this,key)} />
                        {value.title}--
                        <button onClick={this.dellist.bind(this,key)}>删除</button>
                    </li>
                    )
                }
            })
            }</ul><br/>
        </div>
      );
    }
}
export default TodoList;

【App.js】

import React from 'react';
//import logo from './logo.svg';
import './App.css';
import Demo from './components/todolistClass';

function App() {
  return (
    <div className="App">  
        {/*
        <img src={logo} className="App-logo" alt="logo" />
        <Demo3 />
        */}

        <Demo />
    </div>
  );
}
export default App;

效果同上一节

推荐阅读