美文网首页
Hoc Vs Render Props

Hoc Vs Render Props

作者: Ag_fronted | 来源:发表于2021-07-13 16:31 被阅读0次

1、Hoc

import React from 'react'
import ReactDOM from 'react-dom'

const withMouse = (Component) => {
  return class extends React.Component {
    state = { x: 0, y: 0 }

    handleMouseMove = (event) => {
      this.setState({
        x: event.clientX,
        y: event.clientY
      })
    }

    render() {
      return (
        <div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
          <Component {...this.props} mouse={this.state}/>
        </div>
      )
    }
  }
}

const App = (props) => {
  const { x, y } = props.mouse
  return (
    <div style={{ height: '100%' }}>
      <h1>The mouse position is ({x}, {y})</h1>
    </div>
  ) 
}

export default withMouse(App);

2、Render Props

import React from "react";
import ReactDOM from "react-dom";

class RenderPropsComponent extends React.Component {
  state = { x: 0, y: 0 };

  handleMouseMove = (event) => {
    this.setState({
      x: event.clientX,
      y: event.clientY,
    });
  };

  render() {
    const { x, y } = this.state;
    return (
      <div style={{ height: "100%" }} onMouseMove={this.handleMouseMove}>
        {this.props.render(x, y)}
      </div>
    );
  }
}

const App = (props) => {
  return (
    <div style={{ height: "100%" }}>
      <RenderPropsComponent
        render={(x, y) => (
          <h1>
            The mouse position is ({x}, {y})
          </h1>
        )}
      ></RenderPropsComponent>
    </div>
  );
};

export default App;

相关文章

  • Hoc Vs Render Props

    1、Hoc 2、Render Props

  • React HOC(高阶组件)

    首先打个广告,系列文章: 古老的React mixins HOC(高阶组件) render props React...

  • React Render props

    首先打个广告,系列文章: 古老的React mixins HOC(高阶组件) render props React...

  • React Hooks

    首先打个广告,系列文章: 古老的React mixins HOC(高阶组件) render props React...

  • React组件Render Props VS HOC 设计模式

    React的设计模式有很多种,比如无状态组件/表现型组件,有状态组件/容器型组件,render模式组件,高阶组件等...

  • React hooks数据状态管理

    自从去年年底React发布16.8后,React hooks已成为替换render props和HOC代码复用方案...

  • render prop vs HOC vs Hooks

    重复是不可能的,这辈子都不可能写重复的代码。 当然,这句话分分钟都要被打脸。我们烦恼于频繁的增加需求。 虽然我们不...

  • 深入理解render props

    前言 自己对render props\hoc\hook的区别和适用场景都不怎么了解 在写文章前的个人理解: ren...

  • HOC,Render Props, React Hooks简单实

    有三个按钮,每个按钮样式不同,但内容都是0,都有点击事件,点击后自增一,发现有可复用部分,于是分别用了三种方式实现...

  • render props

    了解render props之前先来回顾一下之前学习过的高阶组件HOC,高阶组件是接收一个组件作为参数,返回一个新...

网友评论

      本文标题:Hoc Vs Render Props

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