Summary of React knowledge points (3)

Summary of React knowledge points

Render Props

The purpose of Render Props is to achieve the reuse of component state. Pass a function to component A through props, which returns a component B, so that component B can be rendered in component A (using the state in component A).

1. Use of Render Props

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>移动鼠标!</h1>
        <Mouse render={
    
    mouse => (
          <Cat mouse={
    
    mouse} />
        )}/>
      </div>
    );
  }
}

Second, the essence of JSX

JSXIs React.createElement()syntactic sugar, Babel will JSX translated into a React.createElement()function call, will be compiled into JSX JS code.

Guess you like

Origin blog.csdn.net/wdhxs/article/details/112204913