react

记录一下最近项目常用的api - -

路由跳转两种方式

let url = "/record?cms_key=" + this.cms_key+"&act_key="+this.act_key
    
this.props.history.push(url)
// window.location.href = window.location.origin + "/#/hd_draw/record";

 

获取路由的参数

let params = utils.get_url_params(this.props.location.search);
let urlSearchs = get_url_params(window.location.search);

//子组件内
let params;
if(this.props.props.props != undefined){
  params = utils.get_url_params(this.props.props.props.location.search)
}else{
  params = utils.get_url_params(this.props.props.location.search)
}

 

调用子组件的属性和方法

//父组件
this.refs.myMobileModal.setInfo(this.state.currentRow)

this.props} currentRow={this.state.currentRow}>

//子组件
//获取值
setInfo (val){
    //通过参数取值
    this.setState({
        currentRow: val,
    },() => {
        this.getData()
    })
    if(val.visibel&&val.type=="huafei"){
        this.setState({
            mobileVisible: val,
        })
    }
  }

 

访问父组件的方法

//父组件
refresh(){
    // 这里箭头函数很重要
    return ()=>{
        this.setState({value:"这里是子组件调用的方法"})
    }
  }

this.refresh()}/>

{this.state.value}

//子组件

ref 属性绑定

//通过ref属性,你可获取,实例中的属性方法,甚至可以通过他获取到DOM实例节点this.refs.myInput.getDOMNode()

refs 获取DOM实例

// 输入框获取焦点
this.refs.myInput.focus()

 

this.setState回调

 

//不在回调中使用参数,我们在设置state后立即使用state:
this.state = {foo: 1};
this.setState({foo: 123});
console.log(this.state.foo);


//使用回调  setState的回调函数   相当于componentDidUpdate函数,和生命周期的函数类似。
this.state = {foo: 2};
this.setState({foo: 123}, ()=> {
 console.log(foo);
 // 123
});

//注意:

//setState是异步的!不保证数据的同步。
//setState更新状态时可能会导致页面不必要的重新渲染,影响加载。
//setState管理大量组件状态也许会导致不必要的生命周期函数钩子调用。

 

 

 

移动端加入fastclick

路由

import "babel-polyfill";
import "es6-promise/auto";
import React from "react";
import ReactDOM from "react-dom";
import {
  Provider
} from "react-redux";
import {
  HashRouter as Router,
  Route,
  Switch,
  HashRouter
} from 'react-router-dom'
import fastclick from "./fastclick"
import routers from './routers/index'
import AppRoute from '@components/approute'
import configure from "./middleware/自己的store";

const store = configure({});
ReactDOM.render(
    
      
        {routers.map((route, i) =>
          
        )}
      
    
  , document.getElementById("root"));

if ("addEventListener" in document) {
  document.addEventListener("DOMContentLoaded", function() {
    // 参数可以是任意的dom元素,如果写document.body,说明会将document.body下面的所的元素都绑定fastclick
    fastclick.attach(document.body);
  }, false);
}

在项目中使用防抖

function debounce(method, delay = 500) { // 防抖函数
    let timer = null
    return function () {
        let self = this
        let args = arguments
        timer && clearTimeout(timer)
        timer = setTimeout(function () {
            method.apply(self, args)
        }, delay)
    }
}

调用 的时候

this.goPage = debounce(this.goPage.bind(this),500);
async goPage() {
    let res = await ajax.post()   //...
}

获取父组件传过来的值

componentWillReceiveProps(nextProps) {
        if (!isEmptyObj(nextProps)) {
            this.getDataFromProps(nextProps);
            log({ ps: `planadd_sh` })
        }
    }

// 从父组件中获取数据 
    getDataFromProps(_props) {
        if (_props) {
            let m_key = _props.m_key;
            let dataList = _props[m_key].protectTypeInfo.list
           }
    }

介绍几个用过的插件

import { Modal,TextareaItem, List} from "antd-mobile"; //antd移动端就不多说了

//
页面的title import DocumentTitle from "react-document-title"; //Cookies的获取和设置 import Cookies from 'js-cookie'; //复制 import { CopyToClipboard } from "react-copy-to-clipboard"; <CopyToClipboard text={this.state.copyText||"前端开发"} onCopy={() => { this.goweixin_click(); }} > //在wx中打开 goweixin_click() { let locatUrl = "weixin://"; if (/ipad|iphone|mac/i.test(navigator.userAgent) && UserAgent.app.jietiao == "jietiao") { var ifr = document.createElement("iframe"); ifr.src = locatUrl; ifr.style.display = "none"; document.body.appendChild(ifr); } else { window.location.href = locatUrl; } }

使用swiper

import Swiper from 'react-id-swiper';

let that = this;
        if (!dataList || dataList.length <= 0) {
            return "";
        }
        let radioIndex = this.state.radioIndex;
        const params = {
            slidesPerView: "auto",
            slideToClickedSlide: true,
            mode: 'horizontal',
            freeMode: true,
            getSwiper: (mySwiper) => {
                that.mySwiper = mySwiper; 
                that.mySwiper.slideTo(0);
            }
        }
return (
            
                {dataList.map((item, index) => (
                    
<img src={item.img} onClick={e => { this.setState({ radioIndex: index, radioVal: item.img }, () => { this.mySwiper && this.mySwiper.slideTo(this.state.radioIndex) }) }} />
<Radio key={index} checked={radioIndex == index} className={radioIndex == index ? "active-btn" : "my-radio"} onChange={e => { this.setState({ radioIndex: index, radioVal: item.img }) }}>
))}
) }

先写这些基础 后面学习再加

你可能感兴趣的:(react)