简体   繁体   中英

React Native: Accessing style values using refs

If I have the following render:

 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>
    );
  }

How would I access the backgroundColor style of this.bgRef in an "onPress" callback?

For example, if I wanted the background color to swap between black and white every time the button is pressed, how would I access the current color? I am aware that states could be used to solve this issue, but am wondering if there is a way to do it using refs. Is there a similar method to ref.current.setNativeProps that instead returns the value of specific properties?

EDIT:

I've edited my question to include the entirety of my code:

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
  }
});

This is how you can change styles using ref

this.bgRef.current.style.backgroundColor = 'salmon';
this.bgRef.current.style.color = 'red';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM