Render Props

2020-05-12 17:46 更新
自 1.3.5 起支持

render props 是指一種在 Taro 組件之間使用一個(gè)值為函數(shù)的 prop 共享代碼的簡(jiǎn)單技術(shù)。

具有 render prop 的組件接受一個(gè)函數(shù),該函數(shù)返回一個(gè) Taro 元素并調(diào)用它而不是實(shí)現(xiàn)自己的渲染邏輯。

舉個(gè)例子,假設(shè)我們有一個(gè)組件,它可以呈現(xiàn)一張?jiān)谄聊簧献分鹗髽?biāo)的貓的圖片。我們或許會(huì)使用 <Cat mouse={{ x, y }} prop 來告訴組件鼠標(biāo)的坐標(biāo)以讓它知道圖片應(yīng)該在屏幕哪個(gè)位置。

我們可以提供一個(gè)帶有函數(shù) prop 的 <Mouse> 組件,它能夠動(dòng)態(tài)決定什么需要渲染的,而不是將 <Cat> 硬編碼到 <Mouse> 組件里,并有效地改變它的渲染結(jié)果。

// cat.js
import catImage from './cat.jpg'
class Cat extends Taro.Component {
  static defaultProps = {
    mouse: {
      x: 0,
      y: 0
    }
  }

  render() {
    const { mouse } = this.props;
    return (
      <Image src={catImage} style={{ position: 'absolute', left: mouse.x, top: mouse.y }} />
    );
  }
}

// mouse.js
class Mouse extends Taro.Component {
  constructor(props) {
    super(props);
    this.handleMouseMove = this.handleClick.bind(this);
    this.state = { x: 0, y: 0 };
  }

  handleClick(event) {
    const { x, y }  = event.detail
    this.setState({
      x,
      y
    });
  }

  render() {
    return (
      <View style={{ height: '100%' }} onClick={this.handleClick}>

        {/*
          我們可以把 prop 當(dāng)成一個(gè)函數(shù),動(dòng)態(tài)地調(diào)整渲染內(nèi)容。
        */}
        {this.props.renderCat(this.state)}
      </View>
    );
  }
}

// MouseTracker.js
class MouseTracker extends Taro.Component {
  render() {
    return (
      <View>
        <View>點(diǎn)擊鼠標(biāo)!</View>
        {/*
          Mouse 如何渲染由 MouseTracker 的狀態(tài)控制
        */}
        <Mouse renderCat={mouse => (
          <Cat mouse={mouse} />
        )}/>
      </View>
    );
  }
}

現(xiàn)在,我們提供了一個(gè) render 方法 讓 <Mouse> 能夠動(dòng)態(tài)決定什么需要渲染,而不是克隆 <Mouse> 組件然后硬編碼來解決特定的用例。

更具體地說,render prop 是一個(gè)用于告知組件需要渲染什么內(nèi)容的函數(shù) prop。

這項(xiàng)技術(shù)使我們共享行為非常容易。要獲得這個(gè)行為,只要渲染一個(gè)帶有 render prop 的 <Mouse> 組件就能夠告訴它當(dāng)前鼠標(biāo)坐標(biāo) (x, y) 要渲染什么。

注意事項(xiàng)

render props 是基于小程序 slot 機(jī)制實(shí)現(xiàn)的。 因此它受到的限制和 children 與組合的限制一樣多


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)