React Native:使用refs访问样式值



如果我有以下渲染:

render() {
return (
<View ref={this.bgRef} style={[styles.container, {backgroundColor: "black"}]}> //want to access backgroundColor property
<TouchableOpacity
style={styles.button}
onPress={this.onPress}
><Text>Click Me</Text></TouchableOpacity>
</View>
);
}

如何访问backgroundColorstylethis.bgRef在"onPress"回调?

例如,如果我希望每次按下按钮时背景颜色在黑色和白色之间切换,我该如何访问当前颜色?我知道国家可以用来解决这个问题,但我想知道是否有一种方法可以使用refs来做到这一点。ref.current.setNativeProps是否有类似的方法而是返回特定属性的值?

编辑:

我已经编辑了我的问题,包括我的整个代码:

import * as React from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';
class App extends React.Component {
constructor (props) {
super(props);
this.bgRef = React.createRef()
this.onPress = this.onPress.bind(this);
}
onPress() {
if (this.bgRef.current.style.backgroundColor == "black") {
this.bgRef.current.style.backgroundColor = "white"
} else {
this.bgRef.current.style.backgroundColor = "black"
}
}
render() {
return (
<View ref={this.bgRef} style = {[styles.container, {backgroundColor: "black"}]}>
<TouchableOpacity
style={styles.button}
onPress={() => this.onPress()}
><Text style={styles.paragraph}>Click Me</Text></TouchableOpacity>
</View>
);
}
}
export default App;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
button: {
alignItems: "center",
backgroundColor: "#DDDDDD",
padding: 10
}
});

这是如何使用ref

更改样式的方法
this.bgRef.current.style.backgroundColor = 'salmon';
this.bgRef.current.style.color = 'red';

最新更新