【问题标题】:Understanding render props in ReactJS理解 ReactJS 中的渲染道具
【发布时间】:2020-07-12 16:16:48
【问题描述】:

我主要了解发生了什么,但我不清楚 MouseTracker 组件中的渲染道具到底发生了什么。这就是我认为正在发生的事情;如果我错了,请纠正我:

MouseTracker 正在使用称为鼠标的渲染道具(状态)渲染鼠标组件。鼠标渲染道具返回 Cat 组件(传递给鼠标道具等于鼠标(状态))。

https://reactjs.org/docs/render-props.html

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>
    );
  }
}

【问题讨论】:

    标签: reactjs jsx react-props


    【解决方案1】:

    是的。我认为你是对的。

    渲染道具是一种制作可重用组件的方法,在本例中,您可以传递任何其他 Animal 或几乎所有其他有意义的组件。

    假设您想要一个功能,以便用户可以在一些选项中选择哪个图标适合他们的鼠标跟踪器,render prop 是实现此类功能的最佳方式。

    【讨论】:

      猜你喜欢
      • 2015-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-11
      相关资源
      最近更新 更多