zoukankan      html  css  js  c++  java
  • Render Props

    The term “render prop” refers to a technique for sharing code between React components using a prop whose value is a function.

    <DataProvider render={data => (
      <h1>Hello {data.target}</h1>
    )}/>



    Components are the primary unit of code reuse in React, but it’s not always obvious how to share the state or behavior that one component encapsulates to other components that need that same state


    More concretely, a render prop is a function prop that a component uses to know what to render.

    class Cat extends React.Component {
      render() {
        const mouse = this.props.mouse;
        return (
          <img src="/cat.jpg" style={{ position: 'absolute', left: mouse.x, top: mouse.y }} />
        );
      }
    }
    
    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' }} onMouseMove={this.handleMouseMove}>
    
            {/*
              Instead of providing a static representation of what <Mouse> renders,
              use the `render` prop to dynamically determine what to render.
            */}
            {this.props.render(this.state)}
          </div>
        );
      }
    }
    
    class MouseTracker extends React.Component {
      render() {
        return (
          <div>
            <h1>Move the mouse around!</h1>
            <Mouse render={mouse => (
              <Cat mouse={mouse} />
            )}/>
          </div>
        );
      }
    }
    

      

  • 相关阅读:
    树莓派上跑.NET的segment fault错误
    WiFi、ZigBee、BLE用哪个?
    SQL Server 的字段不为NULL时唯一
    Asp.net 子web application的Session共享
    Gnucash数据库结构
    sql server中的merge
    禁止使用的极限用语
    Git 操作指南
    Excel VBA保护工作表
    WPF多语言化的实现
  • 原文地址:https://www.cnblogs.com/lhs-fight/p/14383550.html
Copyright © 2011-2022 走看看