首页 > 解决方案 > 从类组件访问 App.js 中定义的变量

问题描述

我是 React-Native 的新手。假设我在 App.js 中定义了变量,并且我使用 Green.js 作为按钮的类组件。如何从 Green.js 访问 someBool ?关键是使用状态来改变颜色,但状态必须根据我必须在 App.js 中定义的条件来改变

应用程序.js:

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

绿色.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;

请帮帮我,谢谢!

标签: javascriptreactjsreact-native

解决方案


您应该将其传递给 Green 组件。作为您调用的 App 组件中的 render 方法的回报,<Green />添加一个类似<Green someBool={someBool} />. 在绿色组件中,您可以通过 访问它this.props.someBool


推荐阅读