使用条件反应本机样式

我是第一次使用本机操作。当出现错误时,我试图更改 TextInput 的样式。

我怎样才能使我的代码不那么丑陋呢?

<TextInput
style={touched && invalid?
{height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10, borderWidth: 2, borderColor: 'red'} :
{height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10}}
</TextInput>
108549 次浏览

使用 StyleSheet.create做这样的风格组合,

短信有效文本无效文本设计样式。

const styles = StyleSheet.create({
text: {
height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10,
},
textvalid: {
borderWidth: 2,
},
textinvalid: {
borderColor: 'red',
},
});

然后用一组样式将它们组合在一起。

<TextInput
style={[styles.text, touched && invalid ? styles.textinvalid : styles.textvalid]}
</TextInput>

对于数组样式,后面的样式将合并到前面的样式中,对于相同的键使用覆盖规则。

更新代码如下:

<TextInput style={getTextStyle(this.state.touched, this.state.invalid)}></TextInput>

然后在类组件之外写:

getTextStyle(touched, invalid) {
if(touched && invalid) {
return {
height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10, borderWidth: 2, borderColor: 'red'
}
} else {
return {
height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10
}
}
}

有两种方法,通过内联或调用函数:

1)

const styles = StyleSheet.create({
green: {
borderColor: 'green',
},
red: {
borderColor: 'red',
},
    

});


<TextInput style={[styles.otpBox, this.state.stateName ?
styles.green :
styles.red ]} />
getstyle(val) {
if (val) {
return { borderColor: 'red' };
}
else {
return { borderColor: 'green' };
}
}


<TextInput style={[styles.otpBox, this.getstyle(this.state.showValidatePOtp)]} />