React Native中的三元运算符

2023-12-26

 <Container>
    <Header function1={()=>this.props.navigation.openDrawer()}/>
        <Content>
                {this.state.formInputs.formFeilds.map((data)=>(
                                                {this.state[`${data}`]?<Item floatingLabel success>:<Item floatingLabel>}
                                                <Label>data</Label>
                                                <Input value={data}/>
                                                <Icon name='checkmark-circle' />
                                            </Item>             
                                        ))}

              </Content>
      </Container>
                )

我的 React Native 类的渲染函数中有这个简单的 return 语句

我想用<Item floatingLabel success>当这个this.state[${data}]是真的,否则<Item floatingLabel >当它是假的时候。

所以我使用三元运算符 (?:) 但代码抛出错误

这是保留关键字

所以我转换了{this.state[${data}]?<Item floatingLabel success>:<Item floatingLabel>} to this.state[${data}]?<Item floatingLabel success>:<Item floatingLabel>

现在错误是

>     Unexpected token, expected ,
 (128:5)   126 |                           ))}   
127 |
128 |      </Content>
129 |      ^ </Container>

但如果我渲染像

     <Container>
                    <Header function1={()=>this.props.navigation.openDrawer()}/>
<Content>
        {this.state.formInputs.formFeilds.map((data)=>(
                                        <Item floatingLabel success>
                                        <Label>data</Label>
                                        <Input value={data}/>
                                        <Icon name='checkmark-circle' />
                                    </Item>             
                                ))}

      </Content>

然后代码运行成功。但我需要使用三元运算符。 请提供任何帮助。


或者,您也可以按照以下方式进行操作。

<Container>
  <Header function1={()=>this.props.navigation.openDrawer()}/>
    <Content>
      {this.state.formInputs.formFeilds.map((data)=>(
       <Item floatingLabel success={!!this.state[`${data}`]}>
        <Label>data</Label>
        <Input value={data}/>
        <Icon name='checkmark-circle' />
        </Item>             
        ))}
  </Content>
</Container>

或者,如果您仍然需要使用三元运算符,请尝试如下。

{!!this.state[`${data}`] && <Item floatingLabel success>}
{!this.state[`${data}`] && <Item floatingLabel>}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React Native中的三元运算符 的相关文章

随机推荐