首页 > 解决方案 > 不变违规:文本字符串必须在组件,在 React Native 中使用条件运算符时发生

问题描述

使用条件运算符根据某些条件显示某些组件后,出现此错误。以下是代码。

    {this.state.isOk==false ?  (
    <View>
       <TextInput value={this.state.title } />
       <Text style={LocalStyles.errorText}>{this.state.errorTitle}</Text>
       <TextInput  value={ this.state.company }  />
       <Text style={LocalStyles.errorText}>{this.state.errorCompany}</Text>
       <View>
          <CheckBox value={this.state.isCurrent} /> 
       </View>
       {this.state.isCurrent==false ? (  
       <Date
       value={this.state.from }
       placeholder={strings("user_profile.from")}
       maxDate={moment().subtract(1, "years")}
       onChange={time => {
       this.setState({ from: time });
       }}/>
       <Text style={LocalStyles.errorText}>{this.state.errorDate}</Text> 
) : null}
       <TextInput label={this.state.location}  />
       <Text style={LocalStyles.errorText}>{this.state.errorLocation}</Text>
       <TextInput  multiline={true} value={ this.state.description} />
       <Text style={LocalStyles.errorText}>{this.state.errorDesc}</Text>
    </View>
    ): null}

这是 Text 组件的样式

  errorText: {
    color: "red",
    paddingLeft: 10,
    paddingRight: 10,
    flexDirection: 'row',
  },

标签: react-native

解决方案


在这种情况下,您应该返回一个空的,而不是null像文本一样处理的返回<View/>


推荐阅读