zoukankan      html  css  js  c++  java
  • react项目经验(三)

    react使用if else语句的方法

    ①在函数中使用if else语句,然后调用函数
    export default class Demo extends React.Component {
        state={
            value:"first",
        }
    
        select=()=>{
            if (this.state.value==="first") {
                return <span>第一</span>
            } else if(this.state.value==="second"){
                return <span>第二</span>
            }
        }
        render(){
            return(
                <div>
                    {this.select()}
                </div>
            );
        }
    }
    
    ②使用三目运算符
    

    map语法

    demoData.map((item,index)=>{
        return <div key={index}>{item.name}<div>  //map语法应该设置key={index},不然会报错
    })
    

    关于json字符串,json对象之间的转换

    ①json字符串转json对象
    const str = '{"id":1,"name":"张三","age":12}'
    const strToObj = JSON.parse(str)
    
    ②json对象转json字符串
    const obj = {"id": 1,"name": "张三","age": 12}
    const objToStr = JSON.stringify(obj)
    

    json对象和json字符串的区别

    json字符串:有一种字符串的格式符合json的格式,所以叫做json字符串,字符串格式不能使用点语法
    const str = '{"id":1,"name":"张三","age":12}'
    json对象:json格式的对象,有键值对,键值对都必须使用双引号包裹,使用单引号或不使用引号都不正确。
    const obj = {"id": 1,"name": "张三","age": 12}
    

    判断一个数组是否为空

     JSON.stringify(arr) === '[]'
     arr.length === 0
     +arr === 0
    

    百度编辑器

    百度编辑器
    
    【【配置】】
    npm i ifanrx-react-ueditor -S
    
    
    引入文件包public/static/ueditor     //已上传至博客园文件库中
    
    
    srcindex.js页面添加代码
    window.UEDITOR_HOME_URL = "/static/ueditor/"
    
    
    srcapiconfig.js页面添加代码
    window.__baseHost = "http://192.123.0.123:8080"
    
    
    css样式引入(根据需求自定义的样式)
    .edui-default.edui-editor-toolbarbox{
        box-shadow: none!important;
    }
    .edui-default.edui-editor-toolbarboxouter{
        background-image:-webkit-linear-gradient(top,#fff,#fff)!important;
        box-shadow:none!important;
    }
    .edui-default.edui-editor{
        border-radius: 0!important;
    }
    
    
    publicstaticueditorueditor.config.js页面
    大概25~45行之间:服务器统一请求接口路径
    , serverUrl: "/static/ueditor/php/config.json"
    , imageUrl: 'http://demo.demos.net:6006/api/upload/'  这个改为当前项目的图片接口
    
    
    publicstaticueditordialogsimageimage.js页面
    uploader.on('uploadSuccess', function (file, ret) {
        var $file = $('#' + file.id);
        try {
            var responseText = (ret._raw || ret),
                json = utils.str2json(responseText);
            if (json.code == 0) {
                _this.imageList.push({
                    url: ret.data,    这一行的data改为图片接口返回数据所使用的的命名
                    title: file.name,
                    original: file.name
                });
                $file.append('<span class="success"></span>');
            } else {
                $file.find('.error').text(json.state).show();
            }
        } catch (e) {
            $file.find('.error').text(lang.errorServerUpload).show();
        }
    });
    
    publicstaticueditordialogsimageimage.js页面(360行到370行之间)
    actionUrl = 'http://demo.demos.net:6006/api/upload/'+localStorage.getItem("listid")+'/uploadimage'; //改成图片请求接口
    
    百度编辑器其他功能性改动
    在publicstaticueditorueditor.config.js页面
    
    
    
    【【使用】】
    引入 import ReactUeditor from 'ifanrx-react-ueditor'
    
    
    <ReactUeditor debug  ueditorPath="/static/ueditor" />
    
    
    

    线上部署

    项目部署到线上
    项目 npm run build
    
    打开FileZillaClient
    主机(H): 192.169.0.175
    用户名(U): huihuihero
    密码(W): pass123
    端口(P): 25
    protocol: sftp
    远程站点: /mountdata/demo.huihuidemo.net
    
    本地站点:选中build文件夹,全选右键上传
    
    

    获取验证码倒计时

    state={
        timeOut:false,
        codeTime:60,
    }
    
    verifyCodeGet=()=>{
            this.setState({
                codeTime:60,
            })
            clearInterval(this.waitTime);
            message.success("验证码请求已发送")
            this.waitTime=setInterval(() => { 
                if(this.state.codeTime>1){
                    this.setState({
                        timeout:true,
                        codeTime:this.state.codeTime-1,
                    })
                }else{
                  this.setState({
                      timeout:false,
                    })
                }
              },1000);
        }
    
    <InputGroup compact>
           <Input placeholder="请输入验证码" className="mb-10px" style={{"60%"}}/>
           {this.state.timeOut===true?<Button style={{"40%",padding:0,fontSize:14}}>{this.state.codeTime}秒后可重新发送</Button>:<Button style=                        
    {{"40%",padding:0,fontSize:14}} onClick={this.verifyCodeGet}>获取验证码</Button>}
    </InputGroup>
    

    线转树方法处理特殊数据格式

     /**
         * @name 线转树
         * @param {Array}       ARR             需要处理的数组
         * @param {String}      keyName         作为分类的字段
         */
        Array2Object = (ARR, keyName) => {
            return ARR.reduce((a, b) => {
                const keys = b[keyName];
                if (a[keys] === undefined) { a[keys] = [] };
                a[keys].push(b);
                return a
            }, {})
        },
    //查询对象子级 例:_comp.compName
    const selectFn = (from, selector) => selector.split('.').reduce((prev, cur) => prev && prev[cur], from);
    
    

    内容不易设置时先const一个参数,再调用这个参数

    import { Popover, Button } from 'antd';
    
    export default class Demo extends React.Component{
        
        render(){
    
            const remind = (
                  <div>
                        <p>注意事项1</p>
                        <p>注意事项2</p>
                  </div>
             );
    
            return(
    
                <Popover content={remind} trigger="click">
                     <Button type="primary">点我查看注意事项</Button>
                </Popover>,
    
             )
         }
     }
    提个醒:当content里要写入的数据比较复杂的时候,可以申明一个参数(如这里得remind),
    在这个参数里写入相关数据,content再调用就可以了。另外const可以写在export之外,也可以写在render和return之间
    
    

    创建一个util.js文件,在里面封装公共机制(如获取时间),并在其他页面文件里引入

    1、src/utils/utils.js(创建用于封装公共机制的js文件)
    export default {
        formateDate(time){
            if(!time)return " ";
            let date = new Date(time);
            return date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()+' '+date.getHours()+':'+date.getMinutes()+':'+date.getSeconds();
        },
    }
    2、若index.js页面需要引入公共机制,则
    import Util from '../../utils/utils'
    export default class Header extends React.Component{
        state={}
        componentWillMount=()=>{
            setInterval(()=>{
                let sysTime = Util.formateDate(new Date().getTime());   //util.js里定义了formateDate方法,这里调用
                this.setState({
                    sysTime
                })
            },1000)
        }
        render(){
            return(
                <div>{this.state.sysTime}</div>
            )
        }
    }
    

    给中文进行编码

    encodeURIComponent("安徽")   
    
    编码结果:"%E5%AE%89%E5%BE%BD"
    

    使用jsonp跨域请求百度天气(域名,协议,端口有一个不同即为跨域)

    1、sudo yarn add jsonp --save   //安装jsonp包,正常安装不了时,尝试使用管理员身份安装sudo
    
    2、在src/api/axios.js里进一步封装jsonp
    import JsonP from 'jsonp'   //引入
    export default class Axios {
        static jsonp(options) {    //jsonp传入的是一个对象
            return new Promise((resolve, reject) => {   //promise封装
                JsonP(options.url, {
                    param: 'callback'
                }, function (err, response) {
                    if (response.status == 'success') {
                        resolve(response);
                    } else {
                        reject(response.messsage);
                    }
                })
            })
        }
    }
    
    3、页面里调用
    import axios from '../../axios'   //引入
    
    state={}
    getWeatherAPIData(){
            let city = '合肥';
            axios.jsonp({
                url:'http://api.map.baidu.com/telematics/v3/weather?location='+encodeURIComponent(city)+'&output=json&ak=3p49MVra6urFRGOT9s8UBWr2'    //ak值通过百度地图开放平台注册获取
            }).then((res)=>{
                if(res.status == 'success'){
                    let data = res.results[0].weather_data[0];
                    this.setState({
                        dayPictureUrl:data.dayPictureUrl,
                        weather:data.weather
                    })
                }
            })
        }
    
    
    <img src={this.state.dayPictureUrl}  />
    <div>{this.state.weather}</div>
    
  • 相关阅读:
    使用Spring MVC统一异常处理实战(转载)
    java 异常
    Java 接口和内部类
    JAVA 继承
    Linux中profile(转载)
    java 对象与类
    Java基本的程序结构设计 数组
    Python虚拟机函数机制之位置参数(四)
    Python虚拟机函数机制之参数类别(三)
    Python虚拟机函数机制之名字空间(二)
  • 原文地址:https://www.cnblogs.com/huihuihero/p/11134539.html
Copyright © 2011-2022 走看看