React使用小技巧

1. React 中Toast的使用
方法所在文件夹:node_modules/antd-mobile/lib/toast/index.d.ts
导入: import { List, Button, Modal, Toast } from 'antd-mobile';
使用: Toast.info('解绑?', 1);//参1,提示;参2,显示的秒数
                      show/info/success/fail/offline/loading/hide/config

2. 页面跳转传值 
使用this.props.history.push方法
this.props.history.push({ pathname: '/path', state: { devId:'abc' } });
pathname:写跳转界面的路径
state:要传过去的数据

新页面取值:
this.props.location.state.devId

调试时,刷新页面,会报错:devId未定义,此时应加上this.props.location.state的空值判断

class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      devId : ''
    };
  }
 
  componentWillMount(){
    //if(this.props.location.state){
    const {location} = this.props;
    if (location && typeof(location.state) !== 'undefined') {
      this.setState({
        devId : this.props.location.state.devId,
      })
    }
  }
}  

3. 

定位要和边偏移搭配使用,比如 top: 100px; left: 30px; 等等

边偏移:top/bottom/left/right   //right右侧偏移量,定义元素相对于其父元素右边线的距离

4.

img属于行内块元素,要想img靠右,要用div包裹,同时给div和img设置同样的宽高,这样img就是想要的尺寸了,用margin-right定位右边距

<div className="test-div"> 
	<img className="left-icon" src={require("./imgs/device@2x.png")} />  
</div>

.left-icon {
    width: 50px;
    height: 50px;
}
.test-div {
    width: 50px;
    height: 50px; 
    background: #000;
    /* margin: 0 auto; */
    float: right;
    margin-right: 10px;
}	

5. 用margin:auto实现垂直居中

.father {
    width: 300px; height:150px;
    position: relative;
}
.son {
    position: absolute;
    top: 0; right: 0; bottom: 0; left: 0;
    width: 200px; height: 100px;
    margin: auto;
}

6.手机端调试小工具 vConsole
根index.js中找到<div id="root"></div>
附近添加:
<script src="https://cdn.bootcdn.net/ajax/libs/vConsole/3.3.4/vconsole.min.js" type="text/javascript"></script>
    <script>
      var vConsole = new VConsole();
    </script>

7. .toString()

server端传来的值,类型不定,‘1’ 或 1,接收后统一处理为‘1’,使用.toString()方法

8.  localStorage

页面回退时需要传值,可以使用localStorage

sessionStorage用于本地存储一个会话(session)中的数据,这些数据只有在同一个会话中的页面才能访问并且当会话结束后数据也随之销毁。因此sessionStorage不是一种持久化的本地存储,仅仅是会话级别的存储。

localStorage用于持久化的本地存储,除非主动删除数据,否则数据是永远不会过期的。

页面回退时,不需传值,可以使用  window.location.replace(url: string); , 可防止页面叠加。

JS基础 sessionStorage

js 页面回退 防止页面叠加 url传值

storage事件:Storage 接口储存的数据发生变化时,会触发 storage 事件,可以指定这个事件的监听函数。

注意,该事件有一个很特别的地方,就是它不在导致数据变化的当前页面触发,而是在同一个域名的其他窗口触发。也就是说,如果浏览器只打开一个窗口,可能观察不到这个事件。比如同时打开多个窗口,当其中的一个窗口导致储存的数据发生改变时,只有在其他窗口才能观察到监听函数的执行。可以通过这种机制,实现多个窗口之间的通信。

9. 汉字可分行,字母数字不会分行

  white-space: pre-line;
  word-break: break-all;

10.   适配手机屏幕

<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=no" />   
<meta name="apple-mobile-web-app-capable" content="yes" />  

user-scalable=no : 网页不可缩放

1. 禁止长按:

    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    user-select: none;	

11. 图片引入后显示[object Module]的问题:在你导入图片的后面加上.default

<img src={require('../../asserts/imgs/icon_return_black@3x.png').default}/>                

12.  https://www.imooc.com/video/17881

React 用来创建界面的js库,和界面打交道。相当于mvc的v

node -v //node的版本要大于6.0
npm install create-react-app -g //-g:全局安装,指向当前的环境变量
create-react-app my-project //创建项目
//若提示:create-react-app不是内部或外部命令,也不是可运行的程序,要使用
npx create-react-app my-project 

cd my-project

npm start

ps:构建完项目,要在package.json中增加 "homepage": ".",属性

13. flex

14. title

    <meta charset="UTF-8">
    <title>快来围观:好友家的空气管家,正在检测空气质量</title>

15. 子绝父相居中

.text {
    background-color: chartreuse;
    
    position: absolute;
    left: 50%;
    top: 50%;    
    transform:translate(-50%,-50%);  /* 走的自己的一半 */
}

16. 在html中js如何给字符串中加换行符

const hintStr = '1、很长很长的字符串111111111111111111111;\n2、很长很长的字符串222222222222222。';

    <div style={{margin: '32px 14px 0 14px', whiteSpace: 'pre-line'}}>
        <span>{hintStr}</span>
    </div>

17. js中修改css的属性

18. 背景色 渐变

background-image: linear-gradient(#1856E7, #509CFC);

19. 

yyy.css
className = 'xxx'

防止样式污染
index.js 
index.module.css
styles.xxx

20. Module not found: Error: Can't resolve 'XXX' in 'XXXX'

21. 自定义控件中 this.props.history  undefined - 自定义控件中 要传入 history
  this.props.history.goBack();不可用
  <TitleBar title={'空调'} titleBg={'#ff0'} showRightIcon={true} history={this.props.history}/>

22. 
内边框:要有borderStyle参数
borderStyle: 'solid',
borderWidth: '1px', 
borderRadius: '22px',
borderColor: '#2283E2',

23. 遮罩样式

.more-mask {
  position: fixed;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  background: rgba(0, 0, 0,0.5);
  opacity: 0.5;
  pointer-events: none;
}

1. 走马灯、轮播: antDesign carousel

https://09x.ant.design/components/carousel/

css实现轮播图

修改修改dot颜色和位置//修改组件自带的样式

import {Slider,Carousel} from 'antd-mobile';
const CarouselBtn = styled(Carousel)`
    .slider-decorator-0 {
        top: 124px !important;
    }
    .am-carousel-wrap-dot-active > span {
        background: #2283E2 !important;
        }
    span{
        background: #fff !important;
    }
`;
<CarouselBtn  autoplay infinite >
{                            
[1,2,3].map((idx) => (
(
	<div>                               
		<img src={this.state.RecoImgUrl[idx%(this.state.RecoImgUrl.length)]} alt="" 
			style={{width: '100%', height: '144px', marginTop: '14px', marginBottom: '12px'}}                                       
		/>
		<span style={{marginLeft: '12px', marginRight: '12px', color: '#333', fontSize: '14px', 
			whiteSpace: 'pre-line'}}>
			{this.state.RecoText[idx%(this.state.RecoText.length)]}</span>  
	</div>                
)))
}
</CarouselBtn>

2.  增加字体/字库 
1). src/asserts/fonts/styles.css内增加

@font-face {
    font-family: myFont;
    src: url('./DINALTERNATE.otf'); 
    //src: url('x.ttf');也可
}

2). App.js内引入
import './asserts/fonts/styles.css'
3). 使用

.cardMallImgDiv > div:nth-child(1) > div:nth-child(3),
.cardMallImgDiv > div:nth-child(2) > div:nth-child(3) {
    font-size: 13px;
    font-weight: 900;
    color: #EC2854;
    font-family: myFont;
    margin-top: 4px;
}

1. React 多环境打包 - dotenv -e .env.development 

.env.production:  REACT_APP_BASE_URL = https://x.x.net:1111/
.env.development: REACT_APP_BASE_URL = https://x.x.net/

npm install dotenv-cli --save-dev

  "scripts": {
    "start": "dotenv -e .env.development react-app-rewired start",
    "build": "cross-env GENERATE_SOURCEMAP=false react-app-rewired build && cd ./build && pktool -k alldev_aircondition",
    "test": "react-app-rewired test --env=jsdom",
    "eject": "react-scripts eject"
  },

npm start 

const mode = process.env.REACT_APP_BASE_URL;
console.log('mode',mode) 

https://juejin.cn/post/6844904126170529799
 https://github.com/entropitor/dotenv-cli

2.增加路由

npm install --save react-router-dom

import React from 'react'
import { Switch, Route, withRouter, Router } from 'react-router-dom';
import AddCtrl from './page/addCtrl/AddCtrl';

class App extends React.Component{
  constructor(props){
    super(props);
  }

  render(){
    return(
      <Router history={this.props.history}>
        <Switch>
          <Route path='/' exact component={AddCtrl}/>
        </Switch>
      </Router>
    );
  }
}

export default App;

1). TypeError: Cannot read property ‘location‘ of undefined 报错解决办法 :Router -> HashRouter
    
2). exact 属性

3). npm run build 生成.zip后无法展示界面,要在package.json里增加 "homepage": "." 属性

3. pathname为当前路径时,界面无法跳转

       this.props.history.replace({
            pathname: '/',
        });

4. box-sizing: border-box; border不占宽度

    border:5px solid red;

5. css动画
    https://www.w3school.com.cn/css/css3_animations.asp
    http://www.ruanyifeng.com/blog/2014/02/css_transition_and_animation.html
    使用lottie
     npm install --save react-lottie
     https://www.npmjs.com/package/react-lottie/v/1.0.0
     https://www.jsopy.com/2020/07/15/reactcha2/

6. 事件冒泡和遮罩层事件透传了
pointer-events: none; /* 不接受鼠标事件 */
e.stopPropagation();//阻止事件冒泡

 

es6 `${ }`

modal.prompt alert

.css .less的区别

---

ui适配方案- viewPort : antDesign
mobx状态管理
Router 路由、代码分割:动态引入
uplusApi 逻辑引擎

util: 
    时间库 - Moment
    outils 
    Mock.js
server: axios    
页面调试:vConsole/AlloyLever

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值