条件渲染
-
短路表达式
小程序在短路表达式渲染时,会出现 true 或者 false 的短暂出现,所以如果是要是适配小程序,最好采用 三元表达式 进行判断。 -
三元表达式
比较通用的一种表达式,jsx 语法是不支持 if 操作符的所以只能用三元表达式或者短路表达式。
注意:
1、Taro 是不允许在 render 之外 定义 jsx 。例: 在 render 之外定义个函数 initHtml() {return <Text>文本</Text>}
然后在 render 里的 return {this.initHtml() }
, 这种是错误的。
2、在 jsx 中数组只能直接渲染, 如 {list.map ((item, index) => { return <Text key={index}>项目{item.name}</Text> })}
,不能在渲染过程中进行判断,必须先进行数组处理之后再进行渲染。
Children
Dialog 组件, 使用 this.props.children
来接收传递元素:
1 | import Taro, { Component } from '@tarojs/taro' |
引用 Dialog 组件:
1 | export default class Index extends Component { |
组合:
有些情况你不仅仅需要只传递一个子组件,可能会需要很多个「占位符」。假设 Dialog 有多重情况,可以自定义多个参数组件传递
1 | // Dialog |
注意事项:
不能对 this.props.children
进行操作(即不能改变、逻辑判断等),只读类型。相当于小程序的 slot
功能。在 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
全部都写完整才能实现它的功能。
参考资料:
Taro - 官网: https://taro.aotu.io
Taro - 文档: https://nervjs.github.io/taro/docs/children.html
欣赏此文,打赏一下