一、一个简略的小例子
1.父组件
<Twitter username='tylermcginnis33'> {(user) => user === null ? <Loading /> : <Badge info={user} />}</Twitter>
2.子组件框架
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.子组件具体实现
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); }}
这种模式的劣势在于将父组件与子组件解耦和,父组件能够间接拜访子组件的外部状态而不须要再通过 Props 传递,这样父组件可能更为不便地管制子组件展现的 UI 界面。譬如产品经理让咱们将本来展现的 Badge 替换为 Profile,咱们能够轻易地批改下回调函数即可:
<Twitter username='tylermcginnis33'> {(user) => user === null ? <Loading /> : <Profile info={user} />}</Twitter>