一、一个简单的小例子
1.父组件
<Twitter username='tylermcginnis33'> {(user) => user === null "htmlcode">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>