Detailed explanation of callback rendering mode of React

  • 2021-08-16 23:03:46
  • OfStack

1. 1 Simple little example

1. Parent component


<Twitter username='tylermcginnis33'>
 {(user) => user === null
  ? <Loading />
  : <Badge info={user} />}
</Twitter>

2. Subcomponent Framework


import React, { Component, PropTypes } from 'react'
import fetchUser from 'twitter'
// fetchUser take in a username returns a promise
// which will resolve with that username's data.
class Twitter extends Component {
 // finish this
}

3. Subcomponent implementation


import React, { Component, PropTypes } from 'react';
import fetchUser from 'twitter';
class Twitter extends Component {
 state = {
  user: null,
 }
  static propTypes = {
  username: PropTypes.string.isRequired,
 }
  componentDidMount() {
  fetchUser(this.props.username).then(user => this.setState({user}));
 }
  render() {
  return this.props.children(this.state.user);
 }
}

The advantage of this mode is that the parent component is decoupled from the child component, and the parent component can directly access the internal state of the child component without passing it through Props, so that the parent component can more conveniently control the UI interface displayed by the child component. For example, the product manager asked us to replace the original Badge with Profile, and we can easily modify the next callback function:


<Twitter username='tylermcginnis33'>
 {(user) => user === null
  ? <Loading />
  : <Profile info={user} />}
</Twitter>


Related articles: