react16.3(4)的新特性

一、16.3 >> 16.4

1、修改了getDerivedStateFromProps的触发机制
父组件或自身的update都会触发getDerivedStateFromProps(nextProps, prevState)来返回对象来修改自身的state(16.3只有父组件会触发,为了实现17以后的异步渲染)

getDerivedStateFromProps(np, ps){
  return {
    next: np.next
  }  
  // 相当于
  setState({
     next: np.next  
  })    
}

  

2、ComponentDidUpdate新增了第三个参数snapshot来保存getSnapshotBeforeUpdate返回的对象(16.3新增)

 

 componentDidUpdate (pp, ps, snapshot) {
      // snapshot === {
      //   name: 'haha'
      // }
 }

 3、全新的ref的创建方式,放弃了以前使用回调函数或者字符串的形式(16.3)

1)、createRef

const Child=React.forwardRef((props,ref)=>(
  <input ref={ref} />
))

class Father extends React.Component{
  constructor(props){
    super(props);
    this.myRef=React.createRef();
  }
  componentDidMount(){
    console.log(this.myRef.current);
  }
  render(){
    return <Child ref={this.myRef}/>
  }
}

2)、高阶组件中传递ref

class Child extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return < input / >
    }
}

function logProps(Component) {
    class LogProps extends React.Component {
        componentDidUpdate(prevProps) {
            console.log('old props:', prevProps);
            console.log('new props:', this.props);
        }

        render() {
            const { forwardedRef, ...rest } = this.props;
            return < Component ref = { forwardedRef } { ...rest }/>;
    }
  }
  return React.forwardRef((props, ref) => {
    return <LogProps {...props} forwardedRef={ref} / > ;
  });
}

const LogProps = logProps(Child)

class Father extends Component {  
    constructor(props) {    
        super(props)    
        this.myRef = React.createRef()  
    }  
    render() {    
        return ( <LogProps ref={this.myRef} /> )
 }
}    

  

react 16.3之前HOC的中ref的传递方式

class Child extends Component {
  state = {
    call: 'child'
  }
  render () {
    return (
      <div>Child</div>
    )
  }
}

const setInstance = function (Element) {
  return class extends Component {
    render () {
      const props = { ...this.props }
      const { getInstance } = props
      if (typeof getInstance === 'function') {
        props.ref = getInstance
      }
      return (<Element {...props} />)
    }
  }
}

const Wrapper = function (Com) {
  return class extends Component {
    render () {
      let props = { ...this.props }
      return (<Com {...props} />)
    }
  }
}

const HOC = Wrapper(setInstance(Child))

class Parent extends Component {
  state = {
    call: 'parent'
  }
  componentDidMount () {
    console.log(this.child)
  }
  render () {
    return (
      <div>
        Parent
        <HOC getInstance={(child) => this.child = child}/>
      </div>
    )
  }
}
// 实质上就是this的传递

  

 三、增加了对pointEvent的支持,但自身并不做兼容,需使用第三方插件

即整合了click,touch和触控笔点击的事件使用方法和onClick一样

posted @ 2018-07-12 22:14  lastnigtic  阅读(758)  评论(0编辑  收藏  举报