React进阶笔记

1. 事件监听

React中使用onClick类似的写法来监听事件,注意this绑定问题 react里严格遵循单项数据流,没有数据双向绑定,
所以输入框要设置value和onChange 
handleChange(e){ this.setState({ name:e.target.value }) }
<input type="text" value={this.state.name} onChange={(e)=>this.handleChange(e)} />

2.  PureComponent Vs Component  https://www.jianshu.com/p/c41bbbc20e65

3.  React.memo

React v16.6.0 之后的版本,可以使用 React.memo 让函数式的组件也有PureComponent的功能 
4. HOC(Higher-Order Components) 高阶组件
高阶组件也是一个组件,但是他返回另外一个组件,产生新的组件可以对属性进行包装,甚至重写部分生命周期 
const withKaikeba = (Component) => { const NewComponent = (props) => { return <Component {...props} name="开课吧高阶组件" />; };return NewComponent; };
上面withKaikeba组件,其实就是代理了Component,只是多传递了一个name参数 
5. 高阶组件最巧妙的一点,是可以链式调用。
import React, {Component} from 'react'
import {Button} from 'antd'
const withKaikeba = (Component) => {
    const NewComponent = (props) => {
        return <Component { ...props } name = "开课吧高阶组件" / > ;
    };
    return NewComponent;
};
const withLog = Component => {
    class NewComponent extends React.Component {
        render() {
            return <Component { ...this.props }  />;
        }
        componentDidMount() {
            console.log('didMount', this.props)
        }
    } return NewComponent
}
class App extends Component {
    render() {
        return (
            <div className="App">
                <h2>hi,{this.props.name}</h2 >
                < Button type="primary" > Button < /Button>
                </div >
             )
   }
   }
export default withKaikeba(withLog(App))
6. 高阶组件装饰器写法
npm install --save-dev babel-plugin-transform-decorators-legacy
const { injectBabelPlugin } = require("react-app-rewired");
module.exports = function override(config) {
  config = injectBabelPlugin(
    [
      "import",
      {
        libraryName: "antd",
        libraryDirectory: "es",
        style: "css"
      }
    ],
    config
  );
  config = injectBabelPlugin(
    [
      "@babel/plugin-proposal-decorators",
      {
        legacy: true
      }
    ],
    config
  );
  return config;
};

使用装饰器

import React, { Component } from 'react'
import { Button } from 'antd'
const withKaikeba = (Component) => {
    const NewComponent = (props) => {
        return <Component { ...props } name="开课吧高阶组件" />;
    };
    return NewComponent;
};
const withLog = Component => {
    class NewComponent extends React.Component {
        render() {
            return <Component {  ...this.props } />;
        }
        componentDidMount() {
            console.log(Component.name, 'didMount', this.props)
        }
    } return NewComponent
}
@withKaikeba
@withLog
class App extends Component { render() { return ( <div className="App"> <h2>hi,{this.props.name}</h2 > < Button type="primary" > Button < /Button> </div > ) } } export default App

7. 

猜你喜欢

转载自www.cnblogs.com/it-Ren/p/12219913.html