react js

 

 this.setState 

         同步绑定,  异步更新。

         redux作者,核心成员:为什么异步 1性能,多个更新同步调用render。

                                                                   2  如果同同步更新state,但是还没执行render,这state与props不能保持同步。

        拿到异步数据   A setState 回调函数。 或    B 在render完成后, 调用componentDidUpdate();

        调成同步, 把这个放到setTimeout()=>{} 里。   或用document.getElementById("btn").addEventListener("click",)里

         这里里面有队列,优先级的概念。

       合并                                                    

         this.setState(count:this.count+1 ) 三遍的话, 得到的值只是+1

        不合并         this.setState((prevState,prop)=>{retrun {count:prevState.count+1;})

 

         拦截Render   。 有个函数。 shouldComponentUpdate(newProps,newState,nextContext)         

                        也可以继承  PureComponent。

         函数组件,使用meno。

                   const MenoHeader=meno(function Header(){retrun <h2>我是header组件<h2>});

should

state的属性的不可变力量     -------------------------

     通过shouldComponentUpdate(nextProps,nextState)进行拦截,。或继承   PureComponent

      触发渲染。 是   setstate的时候

    this.state.friendNames.push({name="new",age=18});

     this.setState({ friendName:this.state.friendName});   这种做法是错误的。   因为如果通过shouldComponentUpdate 优化, 就有问题。 里面的代码  if(newState.friendName==this.state.friendName) return true;

    数组取出来放到另一个里面的语法 es6     const newFriends=[...this.state.friends];

 

 

Slot**********************************  

                    parents                                                                        children

    第一种

    <ChildComponent>                                                        <div>

           <span> aaa</span>                                                     {this.props.children[0]}

           <strong> bbb</strong>                                                 {this.props.children[1]}

    第er种

                                                                                            const {leftSlot,rightSlog)=this.props;

    <ChildComponent                                                      <div>

           leftSlot={<span> aaa</span> }                                                   {leftSlot}

           rightSlot={<strong> bbb</strong>    }                                              {rightSlog}

 

全局事件传递                                      event bus          依赖于    yarn add event                  import {EventEmitter} from 'event'

                           sender                                                                      receiver

            const eventBus=new EventEmitter();                                   在 componentDidMount            在   componentWillUnmount的时候卸载掉。

             eventBus.Emit(eventName, varibleArgument);                 eventBus.addListener("sayHello",(args=>{}})    对于多个参数接收的时候, 要用多个形参进行接收。

 

受控与非受控控件

      1 获取dom   在  componentDidMount   用  document.get

           用   ref      <h2 ref="stringName" >     用   this.refs.stringName

                 推荐方式   在构造里  this.titleRef=createRef()    <h2 ref={this.titleRef} >     用   this.titleRef.current

                  在构造里  this.titleEl=null     <h2 ref={(arg)=>this.titleEl=arg} >     用   this.titleEl.innerHtml

                 如果放到组件的时候。可以直接调用组件的方法。 ?? 获得组件里的dom 可以用 react.forwardRef.       hooks里如何使用ref

    2 受控组件

            form  里   <form onSubmit={e=>this.handleSubmit(e)}       <input type="text" id=username onChange={e=>this.handleChange(e)} value={this.state.username} />  

             handleSubmit(event){ event.preventDefault();}         handleChange(event){ this.setState({userName=event.target.value})   可改成通用  Es6的计算属性名 handleChange(event){ this.setState({[event.target.name]=event.target.value})

     3 非受控组件

        通过 ref 直接获取dom 提交

高阶函数   

      高阶函数:   filter  、map  reduce

     高阶组件 Higher-Order components  .  参数为组件, 返回值是新组件的函数        是一种设计模式。 如redux中的connect ;react-router中的withRouter

                 定义一个    function enhanceComponent(wrappedComponent){

                                class NewComponent extends PureComponent{ render(){

                                       return <WrappedComponent {...this.props}    //这是把属性都赋给下一个组件  

                                } 

                                NewComponent.displayName='aaa';    可以显示的名字   

               应用增强props   相当于拦截了。   例如, 增加 context     

                 定义一个    function enhanceWithUserComponent(wrappedComponent){

                                          return (  <UserContext.Consumer>

                                                 {   user=>{  return <WrappedComponent {...this.props} ,{...user}   //这是把属性以及共享数据都赋给下一个组件    。                     

                                }

               渲染鉴权    登录才可渲染   ; 发送网络请求前 loading

               生命周期的劫持      打印渲染事件 。    

               反向继承       就是继承与传进来的组件。  现在不建议。  建议用组合。就是上面的那种

               原先组件   复用  用  mixin 。 现在也不建议用了

               意义: 嵌套可能较多。       Hooks 是未来。

              ref 不能用到函数组件里             forwardRef from react 是个函数  ,多了一个ref 参数.     也可以用hooks  ref

                     const Profile= forwardRef(function(props,ref){ return <p ref={ref}>Profile</p>}

             Portals 的使用    渲染独立于父组件

                   如弹窗  ReactDom.CreatePortal(child,container) 

                           render(){  return ReactDom.CreatePortal(this.props.children,document.getElementByID("")) }    或一般第三方库都是自己创建一个div

            fragment 片段   组件返回只能有一个根。 则可以用fragment作为根代替多余的那个根div。 还可以直接用段语法  <>

            strictmode 严格模式    是一个突出显示潜在问题的工具,只是开发模式。 <React.StrictMode>

                    识别不安全的生命周期       过时的ref API    检查意外的副作用,constructor调用二次 

 

React中的CSS

      组件css   要求   

               有作用域       

               动态添加           
               支持基本的css特性

    内联对象

          style={Font:this.proper}

    css modules   是webpack的特性.  解决局部作用域。 确定, css的名字里不能用-字符。 不方便的动态来修改

         css名字 叫 xxx.module.css.     使用的时候    import homeStye from './style.module'       然后   className={homeStyle.Title}       

    css in js 方案    css的javascript生成的。不是react的一部分,有第三方库提供      react  有人说  all in js   。 反对理论    stop using css in javascript for web development

      样式嵌套, 函数定义    逻辑复用     动态修改状态

          styled-components    这个用的较多      emotion      glamorous                       插件vscode  styled-components 

                 ef6  模板字符串                const name="why" ;   const age =18;  const message='my name is ${name}';

                        标签模板字符串     可以通过模板字符串的方式对一个函数进行调用        function test(...args){ console.log(args)}     

                                          test 'argment'                                                  test 'my name is ${name}, age is ${age}';

                                                                                                                    这面 一个数组,里面有三个值

              使用例子   import styled from 'styled-components'      const Headdiv=    styled.div'                                     //也可以  =styled.div.attrs({aaa:'afafasf'}) 然后再加下面的

        font-size:50px;

                             color:red;' 

                             back-color:${props=>props.bColor}    //动态变class

                             .banner

                        {

             color:#fff;

            &.active{       //   表示当时的.banner 并且是active

              }

            &.hover{       //   伪类

              }

            &.after{       //   伪元素 ,这样后面就加了一个aaa

              content:"aaaa"}                                       

          }

                        <Headdiv> </Headdiv>

        继承   styed(被继承的类)

        设置主题   import {ThemeProvider }            < ThemeProvider theme={{themeColor:"red"}}>      </ThemeProvider>       props.theme.themeColor

      以上    https://space.bilibili.com/412083649?spm_id_from=333.788.b_765f7570696e666f.2

React Redux     React Hooks免费视频教程     https://www.bilibili.com/video/BV1y4411Q7yH/?spm_id_from=trigger_reload

React Hooks   2018年底    16.8     {useState}    原理解析   https://www.bilibili.com/video/BV1iV411b7L1?from=search&seid=5434494190806990577

  {useState} 就是一个  set get 

    function Example (){ const[ count,setCount}=useState(10); return (<div> <p> you click {count} times </p>  <button onClick={()=>{setCount(count+1})

 

 

       创建步骤

  1、首先安装创建react工程的插件:  npm install -g create-react-app

2、到指定目录创建工程    create-react-app first

  

一, -S,-D,-g的解释


npm install module_name -D    即  npm install module_name --save-dev 写入devDependencies 
 
npm install module_name -g 全局安装(命令行使用)  

npm install module_name 本地安装(将安装包放在 ./node_modules 下)

以上都会出现在项目的package.json中 关键就在于安装在哪一个json对象中 如果安装错误很可能会导致 依赖包找不到

从而导致项目error

二, dependencies与devDependencies的区别

  • devDependencies 里面的插件只用于开发环境,不用于生产环境

  • dependencies 是需要发布到生产环境的

yarn add  (remove) axios  @version

yarn add axios react-router-dom react-helmet react-loadable nprogress antd  @ant-design/icons react-redux
yarn add axios react-router-dom react-document-title react-loadable react-custom-scrollbars react-transition-group nprogress antd  @ant-design/icons redux react-redux redux-thunk screenfull js-cookie clipboard 
yarn add react-beautiful-dnd    -- drag 



------------------less 与 jst 里styleName使用 见 https://juejin.cn/post/6938997182045356068
yarn add globby    --glob允许使用规则,从而获取对应规则匹配的文件    globby,是基于 glob
yarn add less -D less-loader@7.3.0 -D postcss-less -D      --less-loader8.0 编译的时候提示 TypeError: this.getOptions is not a function 
yarn add babel-plugin-react-css-modules


react js 默认没有支持@路径,需要在webpack.config.js resove alias 里添加此配置
  • webpack.config.js
  1.  
    resolve: {
  2.  
    ...
  3.  
    alias: {
  4.  
    ...
  5.  
    // 路径引用 @
  6.  
    '@': paths.appSrc,
  7.  
    }
  8.  




https://blog.esunr.xyz/2020/04/%E5%9C%A8React%E4%B8%AD%E4%BD%BF%E7%94%A8%E6%9B%B4%E5%A5%BD%E7%9A%84CSS-Modules/#2-3-%E4%BF%AE%E6%94%B9-css-loader-%E9%85%8D%E7%BD%AE






 

启用 Less 语法编写 CSS  https://www.jianshu.com/p/bfa308164df4

由于 create-react-app 脚手架中并没有配置关于 less 文件的解析,所以我们需要自己进行配置。需要安装的插件 lessless-loader

添加 Less 相关配置

  • 在命令行运行 npm run eject 命令    解决方法:
      1. 修改一下项目
     2. git add .
     3. git commit -m "init"
    4. 再npm run eject 就可以了

    此命令会将脚手架中隐藏的配置都展示出来,此过程不可逆

  • 运行完成之后,打开 config 目录下的 webpack.config.js 文件,找到 // style files regexes 注释位置,仿照其解析 sass 的规则,在下面添加两行代码

  • // 添加 less 解析规则
  • const lessRegex = /\.less$/;
  • const lessModuleRegex = /\.module\.less$/;

修改  const y= (cssOptions,lessOptions, preProcessor) => {    增加了  lessOption

     在这个方法里增加了   

{
loader: require.resolve('less-loader'),
options: lessOptions,
},

找到 rules 属性配置,在其中添加 less 解析配置

!!!注意: 这里有一个需要注意的地方,下面的这些 less 配置规则放在 sass 的解析规则下面即可,如果放在了 file-loader 的解析规则下面,less 文件解析不会生效。

// Less 解析配置
{
    test: lessRegex,
    exclude: lessModuleRegex,
    use: getStyleLoaders(
        {
            importLoaders: 2,
            sourceMap: isEnvProduction && shouldUseSourceMap,
        },
        'less-loader'
    ),
    sideEffects: true,
},
{
    test: lessModuleRegex,
    use: getStyleLoaders(
        {
            importLoaders: 2,
            sourceMap: isEnvProduction && shouldUseSourceMap,
            modules: true,
            getLocalIdent: getCSSModuleLocalIdent,
        },
        'less-loader'
    )
},

此时配置完成,安装 less 和 less-loader 插件即可

$ npm install less less-loader --save



 

 

            

 

7.3.0

less-loader@7.3.0
  • webpack.config.js
  1.  
    resolve: {
  2.  
    ...
  3.  
    alias: {
  4.  
    ...
  5.  
    // 路径引用 @
  6.  
    '@': paths.appSrc,
  7.  
    }
  8.  

posted on 2021-04-02 16:31  developer1980  阅读(122)  评论(0)    收藏  举报

导航