1.基本概念
而 render props 本質實際上是使用到了回調的方式來通信。只不過在傳統的 js 回調是在構造函數中進行初始化(使用回調函數作為參數),而在 react 中,現在可以通過 props 傳入該回調函數,就是我們所介紹的 render prop。
import React, { Component } from "react"; export class ScrollPos extends Component { state = { position: null }; componentDidMount() { window.addEventListener("scroll", this.handleScroll); } componentWillUnmount() { window.removeEventListener("scroll", this.handleScroll); } handleScroll = e => { const scrollTop = e.target.scrollingElement.scrollTop; this.setState((state, props) => { return { position: scrollTop }; }); }; render() { return <div className='scroll'>{this.props.children(this.state.position)}</div>; } } export default ScrollPos;
父組件
import React from "react"; import "./App.css"; import ScrollPos from "./component/ScrollPos"; function App() { return ( <div className="App"> <ScrollPos> {position => <h1>{"Awesome !".substr(0, position * 15)}</h1>} </ScrollPos> <div className="spacer" /> </div> ); } export default App;
示例2:
使用 props 傳回調函數,需要多少回調就需要設置多少個 prop,比如這里 Auth 子組件既需要登錄成功回調又需要登錄失敗回調。
子組件
const Auth= (props) => { const userName = getUserName(); if (userName) { const allProps = {userName, ...props}; return ( <React.Fragment> {props.login(allProps)} </React.Fragment> ); } else { <React.Fragment> {props.nologin(props)} </React.Fragment> } };
父組件
<Auth login={({userName}) => <h1>Hello {userName}</h1>} nologin={() => <h1>Please login</h1>} />
5.淺比較性能優化
class MouseTracker extends React.Component { // 定義為實例方法,`this.renderTheCat`始終 // 當我們在渲染中使用它時,它指的是相同的函數 renderTheCat(mouse) { return <Cat mouse={mouse} />; } render() { return ( <div> <h1>Move the mouse around!</h1> <Mouse render={this.renderTheCat} /> </div> ); } }
* 注:這里也可以直接將 renderTheCat 這個渲染方法變成組件。類似於 下面代碼中的 movies
import Movies from "./components/movies"; <Route path="/movies" component={Movies}/>
注:回調的理解