在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>
完美解決