React Native:如何通过refs访问组件的样式属性值?
React Native 通过 Refs 获取并修改 View 背景色的实现方案
为什么你的当前代码无法工作
在 React Native 中,不能直接通过 ref.current.style 访问原生组件的样式属性——这是 Web React 的特性,React Native 的原生组件不会将样式暴露在这个属性上。所以你读取 this.bgRef.current.style.backgroundColor 会得到 undefined,自然无法完成颜色切换逻辑。
基于 Refs 的可行实现方案
方案一:使用 UIManager 异步获取当前样式
通过 UIManager 提供的 API 可以异步获取原生组件的当前样式,再结合 setNativeProps 修改背景色。
- 导入所需 API:
import { UIManager, findNodeHandle } from 'react-native';
- 修改
onPress方法:
onPress() { const viewNode = findNodeHandle(this.bgRef.current); if (!viewNode) return; // 异步获取当前组件样式 UIManager.getViewStyle(viewNode, (currentStyle) => { const newColor = currentStyle.backgroundColor === 'black' ? 'white' : 'black'; // 通过 setNativeProps 修改背景色 this.bgRef.current.setNativeProps({ style: { backgroundColor: newColor } }); }); }
注意:该方法依赖原生 API,不同平台/Expo 版本可能存在兼容性差异,且是异步操作。
方案二:自行维护当前颜色状态(更推荐)
既然不想用组件 state,可以用类的实例变量来跟踪当前背景色,直接通过 setNativeProps 修改样式,逻辑更简单稳定。
- 在 constructor 中初始化实例变量:
constructor(props) { super(props); this.bgRef = React.createRef(); this.onPress = this.onPress.bind(this); // 初始化当前背景色 this.currentBgColor = 'black'; }
- 修改
onPress方法:
onPress() { // 切换颜色 this.currentBgColor = this.currentBgColor === 'black' ? 'white' : 'black'; // 通过 setNativeProps 更新样式 this.bgRef.current.setNativeProps({ style: { backgroundColor: this.currentBgColor } }); }
这种方式无需依赖原生异步 API,代码更简洁,兼容性更好。
补充说明
setNativeProps是 React Native 中直接修改原生组件属性的方法,不会触发组件重新渲染,适合这种无需更新组件状态的场景。- 虽然你不想用
state,但如果后续需要基于背景色触发其他组件逻辑,使用state仍是更符合 React 范式的方案。
内容的提问来源于stack exchange,提问作者bloohblahguy
相关产品推荐
相关产品推荐

