多端开发框架,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 全部都写完整才能实现它的功能。