繁体   English   中英

从类组件访问 App.js 中定义的变量

[英]Access variables defined in App.js, from class component

我是 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;

请帮帮我,谢谢!

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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