简体   繁体   中英

Access variables defined in App.js, from class component

I'm new to React-Native. Say I have variables defined in App.js and I'm using Green.js as a class component for a button. How is it possible to get access to someBool from Green.js? The point is to use the state to change the color but the state has to change according to a condition I must define in App.js

App.js:

import Green from './components/Green.js'
export default class App extends Component{
    render(){
      let someBool; ....

Green.js:

import React, {Component} from 'react';
import {StyleSheet, Text, View,TouchableOpacity, Button} from 'react-native';
//import App from './App.js'

 class Green extends Component {
     constructor(props){
         super(props)
         this.state={}
         this.state.custum={
            backgroundColor: 'darkgreen'
         }

         setInterval(() => {
             this.setState( {
                 custum:{
                     backgroundColor: 'lightgreen'
                 }
                })
         }, 1000);
     }

    render() {
        return (
            <View style={[styles.greenB, this.state.custum]}>   // I WANT TO USE SOMEBOOL AS A CONDITION HERE
            </View>
        );
      }
    }  
    var styles = StyleSheet.create({
        greenB:{
          padding: 5,
          height: 80,
          width: 80,  
          borderRadius:160,    
          backgroundColor:'green',    
        },
    })
export default Green;

Please help me, Thank you!

You should pass it down to the Green component. In return of the render method in the App component where you called <Green /> add a prop like <Green someBool={someBool} /> . In the Green component you have access to it by this.props.someBool .

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