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 全部都写完整才能实现它的功能。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值