title: Render Props

自 1.3.5 起支持

render props 是指一种在 Taro 组件之间使用一个值为函数的 prop 共享代码的简单技术。

具有 render prop 的组件接受一个函数,该函数返回一个 Taro 元素并调用它而不是实现自己的渲染逻辑。

举个例子,假设我们有一个组件,它可以呈现一张在屏幕上追逐鼠标的猫的图片。我们或许会使用 <Cat mouse={{ x, y }} prop 来告诉组件鼠标的坐标以让它知道图片应该在屏幕哪个位置。

我们可以提供一个带有函数 prop 的 <Mouse> 组件,它能够动态决定什么需要渲染的,而不是将 <Cat> 硬编码到 <Mouse> 组件里,并有效地改变它的渲染结果。

  1. // cat.js
  2. import catImage from './cat.jpg'
  3. class Cat extends Taro.Component {
  4. static defaultProps = {
  5. mouse: {
  6. x: 0,
  7. y: 0
  8. }
  9. }
  10. render() {
  11. const { mouse } = this.props;
  12. return (
  13. <Image src={catImage} style={{ position: 'absolute', left: mouse.x, top: mouse.y }} />
  14. );
  15. }
  16. }
  17. // mouse.js
  18. class Mouse extends Taro.Component {
  19. constructor(props) {
  20. super(props);
  21. this.handleMouseMove = this.handleClick.bind(this);
  22. this.state = { x: 0, y: 0 };
  23. }
  24. handleClick(event) {
  25. const { x, y } = event.detail
  26. this.setState({
  27. x,
  28. y
  29. });
  30. }
  31. render() {
  32. return (
  33. <View style={{ height: '100%' }} onClick={this.handleClick}>
  34. {/*
  35. 我们可以把 prop 当成一个函数,动态地调整渲染内容。
  36. */}
  37. {this.props.renderCat(this.state)}
  38. </View>
  39. );
  40. }
  41. }
  42. // MouseTracker.js
  43. class MouseTracker extends Taro.Component {
  44. render() {
  45. return (
  46. <View>
  47. <View>点击鼠标!</View>
  48. {/*
  49. Mouse 如何渲染由 MouseTracker 的状态控制
  50. */}
  51. <Mouse renderCat={mouse => (
  52. <Cat mouse={mouse} />
  53. )}/>
  54. </View>
  55. );
  56. }
  57. }

现在,我们提供了一个 render 方法 让 <Mouse> 能够动态决定什么需要渲染,而不是克隆 <Mouse> 组件然后硬编码来解决特定的用例。

更具体地说,render prop 是一个用于告知组件需要渲染什么内容的函数 prop

这项技术使我们共享行为非常容易。要获得这个行为,只要渲染一个带有 render prop 的 <Mouse> 组件就能够告诉它当前鼠标坐标 (x, y) 要渲染什么。

注意事项

render props 是基于小程序 slot 机制实现的。 因此它受到的限制和 children 与组合的限制一样多,更多详情请查看文档Children与组合