taro採坑筆記-props傳遞jsx

多端開發框架,taro,採坑點:

1.組件內部的渲染jsx,須以render開頭,比如: renderTitle

class MinePage extends Component {

  // good
  renderLeft () {
    return (
      <Text>left</Text>
    )
  }

  // bad
  right () {
    return (
      <Text>right</Text>
    )
  }

  render () {
    return (
      <View>
        <View>{ this.renderLeft() }</View>
        <View>content</View>
        <View>{ this.right() }</View>
      </View>
    )
  }
}

export default MinePage

這樣子或許體會不是很深刻,都能跑,但是當組件傳遞jsx的時候會爆炸,譬如以下這個簡單的函數式組件例子 LpInput,它在input左右各接收一個參數left、right,父組件可能會傳遞string、jsx等等:

import Taro, {useState} from '@tarojs/taro'
import {View, Text, Input} from '@tarojs/components'
import './index.css'

const LpInput = props => {
  const {placeholder = '請輸入'} = props
  console.log(props)

  return (
    <View className='lp-input'>
      <View className='left'>
        { props.left } // 此處沒有寫 renderLeft
      </View>
      <View className='middle'>
        <Input placeholder={ placeholder } placeholderClass='placeholder-style'/>
      </View>
      <View className='right'>
        { props.right } // 此處沒有寫 renderRight
      </View>
    </View>
  )
}

export default LpInput

調用:

<LpInput left='leftText' right=(<Text>rightText</Text>) />

當父組件傳遞jsx時,taro會拋出異常:

ReferenceError: React is not defined
或
thirdScriptError React is not defined;

必須要以render開頭:renderLeft、renderRight

2.不要對props.children進行任何操作,比如解構:const { children } = props,繼上個例子LpInput

const LpInput = props => {
  const {placeholder = '請輸入', renderRight} = props 
  // renderRight,es6解構,錯誤操作


  return (
    <View className='lp-input'>
      <View className='left'>
        { props.renderleft } // good, 此處沒有做任何操作
      </View>
      <View className='middle'>
        <Input placeholder={ placeholder } placeholderClass='placeholder-style'/>
      </View>
      <View className='right'>
        { renderRight } // bad,使用解構的 renderRight
      </View>
    </View>
  )
}

官網給出的原因:
請不要對 this.props.children 進行任何操作。Taro 在小程序中實現這個功能使用的是小程序的 slot 功能,也就是說你可以把 this.props.children 理解爲 slot 的語法糖,this.props.children 在 Taro 中並不是 React 的 ReactElement 對象,因此形如 this.props.children && this.props.children、this.props.children[0] 在 Taro 中都是非法的。
this.props.children 無法用 defaultProps 設置默認內容。由於小程序的限制,Taro 也無法知道組件的消費者是否傳入內容,所以無法應用默認內容。
不能把 this.props.children 分解爲變量再使用。由於普通的 props 有一個確切的值,所以當你把它們分解爲變量運行時可以處理,this.props.children 則不能這樣操作,你必須顯性地把 this.props.children 全部都寫完整才能實現它的功能。

發佈了38 篇原創文章 · 獲贊 6 · 訪問量 4996
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章