詳解React的回調(diào)渲染模式
一、一個(gè)簡單的小例子
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.子組件具體實(shí)現(xiàn)
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); } }
這種模式的優(yōu)勢在于將父組件與子組件解耦和,父組件可以直接訪問子組件的內(nèi)部狀態(tài)而不需要再通過 Props 傳遞,這樣父組件能夠更為方便地控制子組件展示的 UI 界面。譬如產(chǎn)品經(jīng)理讓我們將原本展示的 Badge 替換為 Profile,我們可以輕易地修改下回調(diào)函數(shù)即可:
<Twitter username='tylermcginnis33'> {(user) => user === null ? <Loading /> : <Profile info={user} />} </Twitter>
到此這篇關(guān)于詳解React的回調(diào)渲染模式的文章就介紹到這了,更多相關(guān)React 回調(diào)渲染內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React?useEffect不支持async?function示例分析
這篇文章主要為大家介紹了React?useEffect不支持async?function示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07基于react項(xiàng)目打包c(diǎn)ss引用路徑錯(cuò)誤解決方案
這篇文章主要介紹了基于react項(xiàng)目打包c(diǎn)ss引用路徑錯(cuò)誤解決方案,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10React使用context進(jìn)行跨級組件數(shù)據(jù)傳遞
這篇文章給大家介紹了React使用context進(jìn)行跨級組件數(shù)據(jù)傳遞的方法步驟,文中通過代碼示例給大家介紹的非常詳細(xì),對大家學(xué)習(xí)React context組件數(shù)據(jù)傳遞有一定的幫助,感興趣的小伙伴跟著小編一起來學(xué)習(xí)吧2024-01-01