日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

react中定義變量并使用方式_React

作者:超級大Bug ? 更新時間: 2023-05-06 編程語言

react定義變量并使用

這里面涉及到了

  • 1、變量如何定義
  • 2、變量如何進(jìn)行改變
  • 3、方法如何調(diào)用

都寫有詳細(xì)的注釋大家可詳細(xì)觀看適合剛學(xué)習(xí)react的新同學(xué)

class Packaging extends React.Component{ // react 類組件
    constructor(props) {
        super(props);
        this.state = {
          // 進(jìn)行變量定義(會vue的同學(xué):這個地方就相當(dāng)于 data 的return里所定義的)
          // 例如
          name:'定義name'
        };
        this.getNameData();// 調(diào)用方法
    }
    // 定義方法-寫這個方法是為了給大家操作一下怎么改變定義的數(shù)據(jù)
    getNameData() {
        http.get('接口名稱').then(res => {
        	// 第一種
            this.setState({ //  使用this.setState來進(jìn)行改變變量
                name: res.data.name
            });
            console.log(this.state.dataObj) // 打印不到的
            // 第二種
            this.setState({
		       name: res.data.name
		    },() => {
		      console.log(this.state.dataObj) // 可以打印到
		    })
        }).catch(error => {
            console.error(error)
        })
    }
    render() {
        return  <div className="className">// className定義div的class名稱
        			{this.state.name}
        		</div>
    }
}

react全局變量的設(shè)置

新建一個 util文件夾 ---> tool.jsx

window._= {
?? ??? ?/**
?? ??? ? * 存儲localStorage
?? ??? ? */
?? ??? ?setStore:(name, content) =>{
?? ??? ??? ?if (!name) return;
?? ??? ??? ?if (typeof content !== 'string') {
?? ??? ??? ??? ?content = JSON.stringify(content);
?? ??? ??? ?}
?? ??? ??? ?window.localStorage.setItem(name, content);
?? ??? ?},
?? ??? ?/**
?? ??? ? * 獲取localStorage
?? ??? ? */
?? ??? ?getStore:(name) => {
?? ??? ??? ?if (!name) return;
?? ??? ??? ?return window.localStorage.getItem(name);
?? ??? ?},
?? ??? ?/**
?? ??? ? * 清除localStorage
?? ??? ? */
?? ??? ?clearStore:() => {
?? ??? ??? ?window.localStorage.clear();
?? ??? ?},
?? ??? ?
?? ??? ?getQueryStringByName: function (name) {
?? ??? ??? ?var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
?? ??? ??? ?var r = window.location.search.substr(1).match(reg);
?? ??? ??? ?var context = "";
?? ??? ??? ?if (r != null)
?? ??? ??? ??? ?context = r[2];
?? ??? ??? ?reg = null;
?? ??? ??? ?r = null;
?? ??? ??? ?return context == null || context == "" || context == "undefined" ? "" : context;
?? ??? ?}
?? ?
}

在入口文件app.jsx里面引入

import ?"util/tool.jsx";

然后在其余的組件里面就可以訪問到這個變量對象:_

總結(jié)

原文鏈接:https://blog.csdn.net/weixin_43609391/article/details/114977960

欄目分類
最近更新