多端开发框架,taro,采坑点:
这样子或许体会不是很深刻,都能跑,但是当组件传递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
官网给出的原因: 请不要对 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 全部都写完整才能实现它的功能。