React Native点击View修改另一View背景色的正确实现方法
React Native点击View修改另一个View背景色的正确实现
你碰到的Attempted to assign to readonly property.错误,是因为StyleSheet.create()生成的样式对象是只读的,不能直接修改它的属性。React Native里动态样式得用状态来管理,下面是正确的实现方式:
核心思路
用React的useState钩子管理wrapper的背景色状态,点击时更新状态,组件重新渲染时自动应用新的背景色。
完整代码
import { StatusBar } from "expo-status-bar"; import { StyleSheet, View, TouchableHighlight } from "react-native"; import { useState } from "react"; // 导入useState钩子 export default function App() { // 定义状态,初始值为红色 const [wrapperBgColor, setWrapperBgColor] = useState("#ff0000"); const changeBgColor = () => { // 更新状态,设置为黑色 setWrapperBgColor("#000000"); }; return ( // 合并静态样式和动态样式 <View style={[styles.wrapper, { backgroundColor: wrapperBgColor }]}> <TouchableHighlight onPress={changeBgColor}> <View style={styles.body}></View> </TouchableHighlight> </View> ); } const styles = StyleSheet.create({ wrapper: { width: 130, height: 130, padding: "4%", justifyContent: "center", alignItems: "center", // 静态backgroundColor可保留,动态样式会自动覆盖它 }, body: { width: "100%", height: "100%", justifyContent: "center", alignItems: "center", backgroundColor: "#ffffff", }, });
关键说明
useState用来创建响应式状态,状态更新时组件会自动重新渲染- 给wrapper的
style属性传入数组,把静态样式styles.wrapper和动态样式{ backgroundColor: wrapperBgColor }合并,动态样式会覆盖静态样式中同名的属性 - 点击
TouchableHighlight时调用setWrapperBgColor更新状态,触发组件重新渲染,从而改变wrapper的背景色
内容的提问来源于stack exchange,提问作者seriously
相关产品推荐
相关产品推荐

