react native如何动态的添加样式
时间: 2024-05-11 22:16:44 浏览: 12
React Native 中可以使用 StyleSheet API 定义静态的样式,也可以在组件中定义内联样式。如果要动态地添加样式,可以使用属性值为对象的 style 属性,例如:
```
import React, { useState } from 'react';
import { View, StyleSheet, TouchableOpacity, Text } from 'react-native';
const MyComponent = () => {
const [style, setStyle] = useState({});
const onPressButton = () => {
setStyle({ backgroundColor: 'red', padding: 10, borderRadius: 5 });
};
return (
<View style={styles.container}>
<TouchableOpacity style={[styles.button, style]} onPress={onPressButton}>
<Text style={styles.text}>Press me!</Text>
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
button: {
backgroundColor: 'blue',
padding: 8,
borderRadius: 3,
},
text: {
color: 'white',
fontWeight: 'bold',
},
});
```
在这个例子中,我们定义了一个 MyComponent 组件,其中有一个 TouchableOpacity 组件,它的样式由 style 属性控制。在 onPressButton 函数中,我们动态地修改了 style 对象,从而改变了 TouchableOpacity 的样式。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)