React Render Callback Pattern(渲染回撥模式)

看風景就發表於2018-09-17

React Render Callback Pattern,渲染回撥模式,其實是將this.props.children當做函式來呼叫。

例如:

要根據user引數確定渲染Loading還是Profile元件

const App = () => {
  return (
    <div>
      <FieldItem username='magalhini'>
        {user => user === null
        ? <Loading />
        : <Profile info={user} />}
      </FieldItem>
    </div>
  );
};

Render Callback Pattern的做法是:

class FieldItem extends React.Component {
  state = { user: null }

  componentDidMount() {
    // We can make an ajax call here, for e.g.
    setTimeout(() => this.setState({
      user: `I have now fulfilled something for ${this.props.username}`
    }), 1500);
  }

  render() {
    // Render the children with a function using state as the argument
    return this.props.children(this.state.user);
  }
}

關鍵是這句 this.props.children(this.state.user),將this.props.chilren當做函式,將user作為引數傳入。

完整程式碼如下:

// Loading component
const Loading = () => <p>Loading...</p>;

// Profile component
const Profile = (props) => <p>{props.info}</p>;

const App = () => {
  return (
    <div>
    <h3>An application</h3>
    <FieldItem username='magalhini'>
      {user => user === null
      ? <Loading /> 
      : <Profile info={user} />}
    </FieldItem>
    </div>
  );
};
  
class FieldItem extends React.Component {
  state = { user: null }
  
  componentDidMount() {
    // We can make an ajax call here, for e.g.
    setTimeout(() => this.setState({
      user: `I have now fulfilled something for ${this.props.username}`
    }), 1500);
  }
   render() {
    // Render the children with a function using state as the argument
    return this.props.children(this.state.user);
  }
}
                   
ReactDOM.render(<App/>, document.getElementById('app'));

 

 

出處:http://blog.ricardofilipe.com/post/react-callback-render-pattern

相關文章