美文网首页
react hooks-我们为什么会在 React 中加入 Ho

react hooks-我们为什么会在 React 中加入 Ho

作者: 芗芗_ | 来源:发表于2020-07-20 21:33 被阅读0次

问题: 我们为什么会在 React 中加入 Hook? 以及如何使用 Hook 写出更好的应用?

1.在组件之间复用状态逻辑很难
React 没有提供将可复用性行为 (状态共享) “附加”到组件的途径(例如,把组件连接到 store)

现有的方案:

  1. Render Props
    将一个组件封装的状态或行为共享给其他需要相同状态的组件
    react提供一个 render prop 来共享组件之间的状态,而不用考虑共享状态只能在父子组件的问题
// A作为一个公共组件 提供公共的状态
class A extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name:'芗芗' };
  }
render <div>{this.props.render( this.state.name)}</div>
}

class  B  extends React.Component {
  render() {
    const name = this.props.name;
    return (
     <div>{name} 来自四川</div>
    );
  }
}

class  C  extends React.Component {
  render() {
    const name = this.props.name;
    return (
    <div>{name} 15岁</div>
    );
  }
}

// 提供了一个 render 方法 让 <A>组件能够动态决定渲染什么,而不是克隆 <A> 组件然后硬编码来解决特定的用例。
class intro extends React.Component {
  render() {
    return (
      <div>
        <A render={name=> (
          <B name={name} />
        )}/>

      <A render={name=> (
          <C name={name} />
        )}/>
      </div>
    );
  }
}

更具体地说,render prop 是一个用于告知组件需要渲染什么内容的函数 prop。重要的是要记住,render prop 是因为模式才被称为 render prop ,你不一定要用名为 render 的 prop 来使用这种模式。

事实上, [任何被用于告知组件需要渲染什么内容的函数 prop 在技术上都可以被称为 “render prop”],尽管之前的例子使用了 render,

我们也可以简单地使用 children prop!记住,children prop 并不真正需要添加到 JSX 元素的 “attributes” 列表中。相反,你可以直接放置到元素的内部

class A extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name:'芗芗' };
  }
  render <div>{this.props.children( this.state.name)}</div>
}

class  B  extends React.Component {
  render() {
    const name = this.props.name;
    return (
     <div>{name} 来自四川</div>
    );
  }
}

class intro extends React.Component {
  render() {
    return (
      <div>
        <A children={name=> (
          <B name={name} />
        )}/>
      </div>
    );
  }
}

// 不用显视添加到 JSX 元素的 “attributes” 列表中
class intro extends React.Component {
  render() {
    return (
      <div>
        <A>
         {name=>{ <B name={name} />}}
        <A/>
      </div>
    );
  }
}
// 可以直接的定义children为function
A.propTypes = {
  children: PropTypes.func.isRequired
};

拓展

react-motion API

初衷:
对于95%的动画组件用例来说,我们使用缓动曲线和持续时间不需要采用硬编码的方式,为你的UI元素设置刚性和阻尼,剩下的就让物理效果来实现,这样就不用关心动画被打断这些小的事情,这也极大的简化了API
这个库还为React的TransitionGroup提供了一个更强大的替代API

react-motion就是使用的render prop的方式,使得传到motion组件的变量(例如x: 1~100), 可以在动画变化的时候实时的,在render组件里面反映出来

例如当box运动到 100px的展示另外一个box

import React, { Component } from 'react'
import { Motion, spring } from 'react-motion'
class Boxanimation extents Component{
  render(){
    return {
      <Motion defaultStyle={{{left:0}}} style={{left:spring(100)}}>
        {
          (style) => <div style={style}>
            style.x === 50 && <p>展示box</p>
          </div>
       }
      </Motion>
    }
  }
}

将 Render Props 与 React.PureComponent 一起使用时要小心

相关文章

网友评论

      本文标题:react hooks-我们为什么会在 React 中加入 Ho

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