zoukankan      html  css  js  c++  java
  • Node.js 之react.js组件-Props应用

    render props是指一种在 React 组件之间使用一个值为函数的 prop 共享代码(个人理解:将组件进行函数化,通过调用组件名实现,组件的利用,以元素的形式调用,并渲染画面)

    具有 render prop 的组件接受一个函数,该函数返回一个 React 元素并调用它而不是实现自己的渲染逻辑。

    具体实例(代码来自官网):URL:https://zh-hans.reactjs.org/docs/render-props.html#___gatsby

    笔记:代码中实现的组件调用,是将一个组件组为一个标签元素,通过props方法,作为新组件的标签引用(以下代码,相同颜色为组件与元素的关系)

    重要的是要记住,render prop 是因为模式才被称为 render prop ,你不一定要用名为 render 的 prop 来使用这种模式。任何被用于告知组件需要渲染什么内容的函数 prop 在技术上都可以被称为 “render prop”.

    / <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: '100%' }} onMouseMove={this.handleMouseMove}>

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

    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 MouseWithCat 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: '100%' }} onMouseMove={this.handleMouseMove}>

            {/*
              我们可以在这里换掉 <p> 的 <Cat>   ......
              但是接着我们需要创建一个单独的 <MouseWithSomethingElse>
              每次我们需要使用它时,<MouseWithCat> 是不是真的可以重复使用.
            */}
            <Cat mouse={this.state} />
          </div>
        );
      }
    }
     
     
    class MouseMove extends React.Component {
      render() {
        return (
          <div>
            <h1>移动鼠标!</h1>
            <MouseWithCat /> //实现以上组件的全部调用
         </div>
        );
      }
    }
     
  • 相关阅读:
    面试题 08.02. 迷路的机器人(C++)
    URI和URL的区别
    Kali Linux自定义分辨率设置
    CentOS最小化安装后配置NAT网络模式
    CentOS7.5安装及最小安装后联网配置--联网配置
    CentOS7.5安装及最小安装后联网配置--系统安装
    基数排序
    归并排序
    堆排序
    简单选择排序
  • 原文地址:https://www.cnblogs.com/yilizhongzi-yilisha/p/11623927.html
Copyright © 2011-2022 走看看