React——04高阶组件之Render Props

Render Props – React

render props 本质上是使用到了回调的方式来通信。只不过在传统的 js 回调是在构造函数中进行初始化(使用回调函数作为参数),而在 react 中,现在可以通过 props 传入该回调函数,也就是现在的 render prop。

官网中给出了一种就是用鼠标移动事件做的一个封装的Render Props方便可以进行复用

看这里的一个代码:(当鼠标放在浏览器可视区的时候会出现对应的鼠标坐标 )

import React, { Component } from 'react'
import  ReactDOM  from 'react-dom'
export default class App extends Component {
    constructor(props){
        super(props)
        this.mouseClick = this.mouseClick.bind(this)
        this.state = {
            x:0,
            y:0
        }
    }
    mouseClick(event){
        this.setState({
            x:event.clientX,
            y:event.clientY
        })
    }
    componentDidMount(){
        window.addEventListener('mousemove',this.mouseClick)
    }
/*     componentWillUnmount(){
        window.addEventListener('mousemove',this.mouseClick)
    } */
    render() {
        return (
            <div>
               <p> {this.state.x + '为x的坐标'}</p>
               <p> {this.state.y + '为y的坐标'}</p>
            </div>
        )
    }
}
ReactDOM.render(<App />,document.querySelector('#root'))

效果如下:

React——04高阶组件之Render Props

再看一个代码:

// <Mouse> 组件封装了我们需要的行为...
class Mouse extends React.Component {
  constructor(props) {
    super(props);
    this.handleMouseMove = this.handleMouseMove.bind(this);
    this.state = { x: 0, y: 0 };
  }

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

  render() {
    return (
      <div style={{ height: '100vh' }} onm ouseMove={this.handleMouseMove}>

        {/* ...但我们如何渲染 <p> 以外的东西? */}
        <p>The current mouse position is ({this.state.x}, {this.state.y})</p>
      </div>
    );
  }
}

class MouseTracker extends React.Component {
  render() {
    return (
      <>
        <h1>移动鼠标!</h1>
        <Mouse />
      </>
    );
  }
}

把Mouse的组件封装我们所需要的行为

React——04高阶组件之Render Props

 但是这里写死过后就不能进行复用,这里是可以由使用组件的地方决定

React——04高阶组件之Render Props

例: 两个组件 一个组件把坐标信息以文字形式显示 一个组件利用坐标信息展示图片

......

上一篇:appium学习笔记04-使用appium获取元素信息


下一篇:Spring扩展点之BeanFactoryPostProcessor