zoukankan      html  css  js  c++  java
  • 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)
    
    <MobileModal ref="myMobileModal" props={this.props} currentRow={this.state.currentRow}></MobileModal>
    
    //子组件
    //获取值
    setInfo (val){
        //通过参数取值
        this.setState({
            currentRow: val,
        },() => {
            this.getData()
        })
        if(val.visibel&&val.type=="huafei"){
            this.setState({
                mobileVisible: val,
            })
        }
      }

    访问父组件的方法

    //父组件
    refresh(){
        // 这里箭头函数很重要
        return ()=>{
            this.setState({value:"这里是子组件调用的方法"})
        }
      }
    
    <Brother refresh={this.refresh()}/>
    <p>{this.state.value}</p>
    
    //子组件
    
    <button onClick={this.props.refresh}>更新父组件</button>

    ref 属性绑定

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

    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(<Provider store={store}>
        <HashRouter>
          <Switch>
            {routers.map((route, i) =>
              <AppRoute key={i} {...route} />
            )}
          </Switch>
        </HashRouter>
      </Provider>, 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"; <DocumentTitle title="前端开发"></DocumentTitle> //Cookies的获取和设置 import Cookies from 'js-cookie'; //复制 import { CopyToClipboard } from "react-copy-to-clipboard"; <CopyToClipboard text={this.state.copyText||"前端开发"} onCopy={() => { this.goweixin_click(); }} > <img className="give-insurance-btn" src={btnUrl}/> </CopyToClipboard> //在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 (
                <Swiper {...params}>
                    {dataList.map((item, index) => (
                        <div key={index} className={radioIndex == index ? "active-img img" : "img"}>
                            <div className="bg-actimg">
                            <img
                                src={item.img}
                                onClick={e => {
                                    this.setState({ radioIndex: index, radioVal: item.img }, () => {
                                        this.mySwiper && this.mySwiper.slideTo(this.state.radioIndex)
                                    })
                                }}
                            /></div>
                            <Radio
                                key={index}
                                checked={radioIndex == index} className={radioIndex == index ? "active-btn" : "my-radio"}
                                onChange={e => { this.setState({ radioIndex: index, radioVal: item.img }) }}>
    
                            </Radio>
                        </div>
                    ))}
                </Swiper>
            )
        }

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

  • 相关阅读:
    Composite in Javascript
    Model Validation in Asp.net MVC
    HttpRuntime.Cache vs. HttpContext.Current.Cache
    Controller Extensibility in ASP.NET MVC
    The Decorator Pattern in Javascript
    The Flyweight Pattern in Javascript
    Model Binding in ASP.NET MVC
    Asp.net MVC
    jQuery Ajax 实例 全解析
    ASP.NET AJAX入门系列
  • 原文地址:https://www.cnblogs.com/yangsg/p/12778615.html
Copyright © 2011-2022 走看看