美文网首页
React 爬坑记录(随时更新)

React 爬坑记录(随时更新)

作者: E微客 | 来源:发表于2019-08-01 16:19 被阅读0次

简单背景

之前使用的是Vue,由于公司开发的新项目,UI 设计用到了内部组件库,仅支持 React 框架,所以转而学习 React,为避免之后重复遇到类似问题,因此做个简单的爬坑记录。

启动

  • Node:v10.15.2
  • 创建项目:注意 project-name 不能有大写字母,也不能用驼峰命名法
    npx create-react-app project-name
    npx 是 npm 内部自带的安装工具,使用这种方式可以不必全局安装 create-react-app。
  • 运行项目:想更换 start 这个名字,可以在 package.json 中修改
    npm start
    注意,必须 cd 至 project-name 目录下
  • 安装 React 路由
    npm install --save react-router or npm install --save react-router-dom
    react-router 与 react-router-dom 使用时的区别
  • 安装 sass(若使用 less 同理)
    npm install node-sass --save-dev
  • 配置路径,即使用 “@” 符号代替 “src”,好处是不再使用相对路径,代码方便迁移
    1.首先创建 Git 仓库,运行 git initgit add -ugit commit -m '',这是必须的一步
    2.然后运行npm run eject,注意,此过程不可逆,运行后终端也会提示确认命令, 输入Y确认后,会安装一大堆依赖,package.json 文件狂飙到一百三十多行,这里就不截图了,太占地方。
    这里的依赖会安装至 dependencies 下,不过在运行npm run build命令打包时不会把所有包都加载进去,此步只是用来显示 webpack 配置项,方便修改。
    3.运行命令后会生成两个文件,分别是 configscripts,我们找到config下的webpack.config.js打开,如下图:
    image.png
    4.搜索alias并添加代码,路径可以自由定义,如下所示:
    alias: {
        // Support React Native Web
        // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
        'react-native': 'react-native-web',
        '@': path.resolve(__dirname, '../src')
    },
  • 安装 React Developer Tools,这步非必选,目的是在控制台调试 React 项目时可以方便的看到组件列表,如下所示:
    image.png
    安装方法:直接在 Chrome 浏览器中的网上应用商店搜索这个名字,点击下载安装即可,应用商店入口在:浏览器右上角是三个点 -> 更多工具 -> 扩展程序 -> 左上角图标 -> 底部链接(这样都找不到的就退坑吧 = - =)

问题与解决方式

  • 尝试将 react-router 封装至单独的文件中,报错如下:
    Please use require("history").createBrowserHistory instead of require("history/createBrowserHistory"). Support for the latter will be removed in the next major release.
    修改前代码:
import {lazy} from 'react';
const Home = lazy(() => import('@/views/Home'))
import createHistory from 'history/createBrowserHistory';
export const history = createHistory();
export const routes = [ ... ]

修改后代码:

import {lazy} from 'react';
const Home = lazy(() => import('@/views/Home'))
import { createBrowserHistory } from 'history';
export const history = createBrowserHistory();
export const routes = [ ... ]
  • react 的 <img /> 标签中 src 属性设置无效,图片不显示问题
    解决办法:
    第一种方式:Import 导入后引用
import img from "@/assets/top_bg.png"
<img src={img} alt=""/>

第二种方式:require 直接引用

<img src={require('@/assets/top_bg.png')} alt=''/>

第三种方式:尝试在 utils 中封装公有方法,遍历 assets 下所有图片名称和路径,以 key-value 的方式存储,页面中调用方法取出对应图片即可,代码如下:

// 写在 utils 中的公共方法  (待优化)
getImgs = () => {
  const requireContext = require.context("@/assets", true, /^\.\/.*\.png$/);
  const projectImgs = requireContext.keys().map(requireContext)
  let imgs = {}
  for (let i = 0; i < projectImgs.length; i++) {
    const key = requireContext.keys()[i];
    let nameUrl = key.split('./')[1]
    let name = nameUrl.split('.')[0].replace(/\//g, "_")
    const element = projectImgs[i];
    imgs[name] = element
  }
  return imgs
}
// 在页面中引用:
import Utils from '@/utils/utils.js'
<img src={Utils.getImgs().top_bg} className='img-bg' alt=''/>

生成的数据格式如下图:


image.png

注意:图片路径必须是图中显示的 /static/media/***.*** 格式,否则和直接填入路径没有区别,都不会显示,该路径可以直接用 requireContext.keys().map(require.context("@/assets", true, /^\.\/.*\.png$/)) 来获取,后续数据处理因人而异,这里只是举个例子。

  • 顶部导航栏,动态添加 className:直接上 ES6 语法
<li className={`menu-item ${menuIndex === index ? "menuActive" : null}`}>{item}</li>
  • 在 for 循环中动态更改样式
function NewsList(props) {
  const newsArr = props.newsArr;
  const listItems = newsArr.map((item, index) =>
    <li className='news-item' key={index} style={{borderTop: (index === 0) ? 'none' : '1px solid #dee2f8'}}>
      <p className="news-content ellipse">{item.content}</p>
    </li>
  );
  return (
    <ul className="news-list">{listItems}</ul>
  );
}
  • 组件之间传递鼠标事件,子组件调用父组件的事件并传入自定义参数(搞了好久。。)
// 父组件
<ImgsList contentArr={this.state.contentArr}  onMouseEn={this.handleMouseEnter}></ImgsList>
// 子组件
function ImgsList(props) {
  let contentArr = props.contentArr
  const listItems = contentArr.map((item, index) =>
    <li onMouseEnter={()=>{props.onMouseEn(index)}} key={index}></li>
  );
  return (
    <ul className="img-box">{listItems}</ul>
  );
}

注意:子组件中的事件必须使用 function_name={ () => {} } 这种函数的方式,否则默认都是普通函数,不会触发鼠标事件

  • 在 JSX 中进行条件渲染,类比 Vue 的 v-if 功能
<div>
      <p className='title'>条件渲染</p>
      { conidtion &&
          <p className='content' >{item.content}</p>
      }
</div>
  • Expected an assignment or function call and instead saw an expression no-unused-expressions
    代码如下:
function CardItem(props) {
  const listItems = cardArr.map((item, index) => {
    <li className="card-item" key={index}>
      <div className="text-box">
        <p className='title'>{item.title}</p>
        <p className='content'>{item.content}</p>
        <div className="btn-box">
          <Button type='primary' className='btm-button'>免费试用</Button>
          <Button type='primary' className='btm-button right-button'>文档介绍</Button>
        </div>
      </div>
    </li>
  })
  return (
    <ul className="card-box">{listItems}</ul>
  )
}

产生错误的原因是因为没有返回值,锁定第二行,把结尾的那个配套的大括号删掉,直接把内容作为返回值继续,解决

function CardItem(props) {
  const listItems = cardArr.map((item, index) => 
    <li className="card-item" key={index}>
      <div className="text-box">
        <p className='title'>{item.title}</p>
        <p className='content'>{item.content}</p>
        <div className="btn-box">
          <Button type='primary' className='btm-button'>免费试用</Button>
          <Button type='primary' className='btm-button right-button'>文档介绍</Button>
        </div>
      </div>
    </li>
  )
  return (
    <ul className="card-box">{listItems}</ul>
  )
}
  • npm run build 编译打包后页面空白
    解决办法:使用 HashRouter HashHistory 替换 BrowserRouter BrowserHistory

相关文章

  • React 爬坑记录(随时更新)

    简单背景 之前使用的是Vue,由于公司开发的新项目,UI 设计用到了内部组件库,仅支持 React 框架,所以转而...

  • 适配iPhoneX全系详解,更新Xcode10爬坑

    适配iPhoneX全系详解,更新Xcode10爬坑 适配iPhoneX全系详解,更新Xcode10爬坑

  • 记录react-app-rewired 爬坑

    创建react 项目 2.方法1: react -cli 自带的webpack 配置 显示的方法:可以再包文件找到...

  • 【APP设计】React-Native之Ant Design M

    小白入坑React-Native,由于错误太多了。而且重复又容易忘,所以打算开坑写点采坑记录 React-Nati...

  • react-native组件学习

    react-native组件爬坑 activityIndicatoranimating属性如果一开始为false的...

  • React爬坑总结

    react脚手架快速创建react项目 方法一: 1.本地安装node.js/npm 此步省略 npm inst...

  • react native 爬坑

    1.Unable to resolve module 'AccessibilityInfo' 的解决方案解决:最终...

  • 爬坑记录

    在使用knockout的同时也遇到了一系列的问题,在此一下总结,并且日后会持续的更新与跟踪。 view model...

  • 爬坑记录

    1、bytes与hex之间的转换 hex转化为bytes bytes转换为hexdata.hex()

  • React-Native入坑积累

    小白入坑react-native,开贴记录遇到的问题,防止重复错误,以及方便以后查阅,长期更新。一、新建一个项目,...

网友评论

      本文标题:React 爬坑记录(随时更新)

      本文链接:https://www.haomeiwen.com/subject/oyofdctx.html