【问题标题】:Access variables defined in App.js, from class component从类组件访问 App.js 中定义的变量
【发布时间】:2020-05-02 11:30:18
【问题描述】:

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

请帮帮我, 谢谢!

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    您应该将其传递给 Green 组件。 作为调用 &lt;Green /&gt; 的 App 组件中的渲染方法的回报,添加类似 &lt;Green someBool={someBool} /&gt; 的道具。在绿色组件中,您可以通过this.props.someBool 访问它。

    【讨论】:

      猜你喜欢
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-13
      • 2022-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多