我是新来的本地人.我正在尝试在出现错误时更改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>
Run Code Online (Sandbox Code Playgroud)
Val*_*Val 89
用StyleSheet.create做喜欢这种风格组成,
为文本,有效文本和无效文本创建样式.
const styles = StyleSheet.create({
text: {
height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10,
},
textvalid: {
borderWidth: 2,
},
textinvalid: {
borderColor: 'red',
},
});
Run Code Online (Sandbox Code Playgroud)
然后将它们与样式数组合在一起.
<TextInput
style={[styles.text, touched && invalid ? styles.textinvalid : styles.textvalid]}
</TextInput>
Run Code Online (Sandbox Code Playgroud)
对于数组样式,后者将合并为前者,并使用相同键的覆盖规则.
有两种方法,内联或调用函数:
1)
const styles = StyleSheet.create({
green: {
borderColor: 'green',
},
red: {
borderColor: 'red',
},
});
<TextInput style={[styles.otpBox, this.state.stateName ?
styles.green :
styles.red ]} />
Run Code Online (Sandbox Code Playgroud)
getstyle(val) {
if (val) {
return { borderColor: 'red' };
}
else {
return { borderColor: 'green' };
}
}
<TextInput style={[styles.otpBox, this.getstyle(this.state.showValidatePOtp)]} />
Run Code Online (Sandbox Code Playgroud)
如下更新代码:
<TextInput style={getTextStyle(this.state.touched, this.state.invalid)}></TextInput>
Run Code Online (Sandbox Code Playgroud)
然后在类组件之外,编写:
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30767 次 |
| 最近记录: |