React使用过程知识点随手记

205 阅读5分钟

本人主要使用后端Java语言,也对前端react有兴趣,作为一个新手,未能进行系统的前端学习,因此,此文只能将使用React过程的一些零散的步骤过程记录下来,以便查询,如有错误,请指正

react入门学习官网:reactjs.org/docs/gettin…

0.create-react-app新建项目

如:create-react-app accdemotest
npm&yarn&reactjs环境及支持create-react-app命令,可参考npm&yarn&reactjs环境安装并搭建我的第一个helloword项目

1.弹出配置

新建了create-react-app项目后,默认的配置较少,通过yarn eject或npm run eject弹出配置,执行成功后将多出config和scripts两个文件夹。

npm run eject

2.添加路由模块

yarn add react-router-dom 官网文档地址:https://reactrouter.com/web/guides/quick-start

3.修改webpack配置,让引入模块支持src写法

引入组件时,如果想通过指定到项目里面的src目录下的写法,需要设置webpack.config.js的src参数,否则没有加的话,会报错。

##在webpack.config.js中加入
'src': path.resolve(__dirname,'../src'),

在这里插入图片描述 注:不加以上配置的话,编绎会报错,如下在这里插入图片描述加上配置后编绎不再有问题。

4.如何修改react的默认访问端口3000

yarn start 启动后,默认的访问端口号是3000,如果希望改它,通过start.js中的配置属性来完成修改。如果找不到start.js,通过npm run eject先弹出配置,然后再操作, const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000; 在这里插入图片描述

5.export和export default的区别

##export与export default都可用于导出常量、函数、文件、模块等
##在一个文件或模块中,export、import可以有多个,export default仅有一个
##通过export方式导出,在导入时要加{ },export default则不需要

##比如以下写法,没有export default:

import React, { Component } from 'react';
export class Welcome extends Component {
  render() {
    return <h1>hello, {this.props.name}</h1>;
  }
}

以上的写法,没有default,在引入时写成import Welcome from 'src/components/Welcome.js'会报错,只能写成:

import {Welcome} from 'src/components/Welcome.js'

##又比如以下写法,通过export default写的:

import React, { Component } from 'react';
class Welcome extends Component {
  render() {
    return <h1>hello, {this.props.name}</h1>;
  }
}
export default Welcome

以上的写法,通过export default暴露,在引入时写成import Welcome from 'src/components/Welcome.js',编绎正常,并且,可以在引入时随便改名称,如下,将组件的名称改成了Welcometest这样的写法。

import { Component } from 'react';
import Welcometest from 'src/components/Welcome.js'
class App extends Component {
  render() {
    return (
      <div>
        <Welcometest name="john" />
      </div>
    );
  }
}
export default App;

6.react中dangerouslySetInnerHTML使用

带有html标签的字符串内容,默认是会保留原有的标签样式,并不会正确展示,如果需要通过html标签渲染效果,可以使用dangerouslySetInnerHTML,示例代码如下:

import { Component } from 'react';
class App extends Component {
  render() {
    let htmlStr = "<span style='color:red'>span content test&gt;</span>";
    return (
      <div>
        <div>{htmlStr}</div>
        <div dangerouslySetInnerHTML={{__html:htmlStr}} />
      </div>
    );
  }
}
export default App;

效果如下加了dangerouslySetInnerHTML后的能进行相应的样式显示: 在这里插入图片描述

7.react-native-uuid使用

  1. ##安装install

npm install react-native-uuid 或 yarn add react-native-uuid

  1. ##Create a UUID
import uuid from 'react-native-uuid';
uuid.v4(); // ⇨ '64b777b6-2746-410c-ae07-fe599bbef0f6'

8.yarn打包及部署到生产环境.

采集yarn build和nginx进行生产环境的前端代码部署,步骤如下:

  1. ##打包,打包完成后将在源码目录下多出build文件夹,即为打包后的部署文件夹
yarn build
  1. ##部署到nginx,放在某个目录,然后通过nginx代理出来,nginx配置示例如:,重启nginx后通过http://ip:8443/访问。
    server {
        listen       8443;
        server_name  localhost;
        location / {
            root /home/testuser/fe/build;
            proxy_connect_timeout 30;
            proxy_http_version 1.1;
            proxy_send_timeout 60;
            proxy_read_timeout 60;
            try_files $uri $uri/ /index.html = 404;
        }
    }

9.history.push(跳转到其他页面)

一种跳转到其他页面的写法,通过history.push过去,并且通过参数传过去,在另一个页面可以直接获取使用

##跳转页面通过
##传参数
this.props.history.push({pathname:'/detail',datas:{tmpAuthCode: 'xxxxxxxx', clientType: "dingTalkScanningCode"}});
##不传参数
this.props.history.push('/detail');

##到跳转页面后,想接收参数时:
console.log(this.props.location.datas);

10.react中解决this指向问题的四种方法

  1. ##行间定义事件后面使用bind绑定this
	run(){
	    alert("第一种方法!")
	}
  	<button onClick={this.run.bind(this)}>第一种</button>
  1. ##构造函数内部声明this指向
	constructor(props) {
		super(props);
		this.state={
			//数据
		}
		this.run = this.run.bind(this);
	}
	
 	run(){
        	alert("the second method!")
 	}
 	 
 	<button onClick={this.run}>the second method</button>
  1. ##声明事件时将事件等于一个箭头函数
	run = ()=> {
    	alert("第三种方法!")
  	}

	<button onClick={this.run}>第三种</button>
  1. ##行间定义事件使用箭头函数
 	run(){
    	alert("第四种方法!")
  	}

	<button onClick={()=>this.run()>第四种</button>

我喜欢用第三种

11.解决vscode单击新文件时覆盖旧文件问题

将workbench.editor.enablePreview设置为fasle

"workbench.editor.enablePreview": false,

在这里插入图片描述

12. lodash工具库

lodash是一套工具库,内部封装了很多字符串、数组、对象等常见数据类型的处理函数。
官网地址:https://www.lodashjs.com/

示例:如字符串转数组,然后判断数据中有没有 .indexOf(.split(localStorage.roleIds, ','), record.id+'' ) == -1

13.Js自动登陆示例(普通javascript)

<!DOCTYPE html>
<html>

<body>

    <form action="http://116.11.11.114:8180/hpflow/Home/Login" id="frm" method="post" style="display: none;">
        First name:<br>
        <input type="text" name="account" value="user">
        <br>
        Last name:<br>
        <input type="text" name="pwd" value="123456">
        <br><br>
        <input id="submit" type="submit" value="Submit">
    </form>
</body>
<script>
    document.getElementById("submit").click();
</script>

</html>

14.函数组件编写示例

实现了一个按钮权限的控制组件,通过传入一个唯一的按钮编码,通过后端程序控制此按钮的授权,前端通过接口查询当前用户是否具有此按钮的权限,来显示或不显示。

import React, { Fragment } from "react";
import api from "src/api";
import axios from 'axios';
import { message } from 'antd';
import { useEffect, useState } from 'react';
/***
 * 传入一个buttonUniqueCode参数,判断是否显示组件的childRen,主要用于权限按钮控制
 */
export const AuthShow = props => {
    const [show, setShow] = useState(false);

    //获取按钮权限数据,并设置到show变量中
    const getButtonAuthData = () => {
        
        api.sysButton.checkCurrentUserButtonAuthByCode({
            data: {
                buttonUniqueCode: props.buttonUniqueCode,
            },
        })
        .then(res => res.data)
        .then(json => {
            if (json.success) {
                setShow(json.data);
            } else {
                message.error(json.message);
            }
        })
        .catch(err => console.error(err));
        
    };

    useEffect(() => {
        getButtonAuthData();
    },[]);

    return show != true ? (
        <Fragment></Fragment>
    ): (
        <Fragment>
            {props.children}
        </Fragment>
    )
};
其中的`useEffect(() => {
        getButtonAuthData();
    },[]);` 加上`[]`的作用是让组件只加载一次,这个位置的参数数组是函数执行的依赖,空数组只会在渲染的时候执行一次,如果没有加依赖,每次组件重新渲染都会执行

##在需要进行按钮控制的地方进行引用控制,比如:

<AuthShow buttonUniqueCode='useManageInsert'>
    <Button onClick={() => showModal('mail')}>
        <Icon type="folder-add" />
        新增用户
    </Button>
</AuthShow>

其他react使用过程知识点会不断整理记录并持续更新.....