在taro的jsx中,鉴于编译的机制,官方明确的表示了不能在map循环中使用if循环,
但是呢,官方也给出了解决办法,那就是提取变量或者是用三目运算嵌套的方法:
链接奉上:https://github.com/NervJS/taro/blob/master/packages/eslint-plugin-taro/docs/if-statement-in-map-loop.md
但是我再想,如果我有多个条件去判断呢,难道我只能去进行三目套三目吗?
如下(使用的简单的ts):
import Taro, {Component} from '@tarojs/taro' import {View, Text, Button} from '@tarojs/components' import connect from "../../containers/counter" import {ComponentClass} from "react"; type PageOwnProps = { } type PageStateProps = {} type PageState = { listArr: string[] } type IProps = PageOwnProps & PageStateProps interface List { props: IProps, state: PageState } @connect class List extends Component { constructor() { super(...arguments); this.state = ({ listArr: ["one", "two", "three"] }) } public render() { return ( <View className={'index'}> { this.state.listArr.map((item, index) => { return index === 0 ? <View>index =0 item is {item}</View> : index === 1 ? <View>index = 1 item is {item}</View> : null }) } </View>) } } export default List as ComponentClass<PageOwnProps, PageState>
确实可以达到效果,但是这样写起来层级嵌套的很深了,很不好看,在咨询了taro作者隔壁老李以后,把循环的内容抽出来做子组件,把index和item,当作参数传递给子组件,在子组件里面使用if即可:
import Taro, {Component} from '@tarojs/taro' import {View, Text, Button} from '@tarojs/components' import connect from "../../containers/counter" import {ComponentClass} from "react"; import ListItem from './listItem' type PageOwnProps = { } type PageStateProps = {} type PageState = { listArr: string[] } type IProps = PageOwnProps & PageStateProps interface List { props: IProps, state: PageState } @connect class List extends Component { constructor() { super(...arguments); this.state = ({ listArr: ["one", "two", "three"] }) } public render() { return ( <View className={'index'}> {this.state.listArr.map((item, index) => { return <ListItem propIndex={index} propItem={item}> </ListItem> })} </View>) } } export default List as ComponentClass<PageOwnProps, PageState>
子组件listItem.tsx:
import {ComponentClass} from 'react' import {Component} from '@tarojs/taro' import {View} from '@tarojs/components' type PageStateProps = { counter: {} } type PageDispatchProps = {} type PageOwnProps = { propIndex: number, propItem: any } type PageState = {} type IProps = PageStateProps & PageDispatchProps & PageOwnProps interface ListItem { props: IProps; state: PageState } class ListItem extends Component implements ListItem { render() { let resultDom: any = null; if (this.props.propIndex === 2) { resultDom = <View> prop is 2 ,item is {this.props.propItem} </View> }else{ resultDom = <View> prop is no 2 ,item is {this.props.propItem} </View> } return ( <View> {resultDom} </View> ) } } export default ListItem as ComponentClass<PageOwnProps, PageState>
完美解决