javascript - 从类组件访问 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;
请帮帮我,谢谢!
解决方案
您应该将其传递给 Green 组件。作为您调用的 App 组件中的 render 方法的回报,<Green />
添加一个类似<Green someBool={someBool} />
. 在绿色组件中,您可以通过 访问它this.props.someBool
。
推荐阅读
- java - 使用 AJAX 选择重新加载 div 后的 Spring / Thymeleaf 模板问题(*localidad 的问题)
- node.js - 在创建反应项目时在“npx create-react-app my-app”之后运行命令“npm start”时出错
- wpf - 如何将工具提示放在按钮上以在 WPF 中启用和禁用
- amazon-web-services - 带有 ssl 的单个 alb 后面的私有子网中的几个域
- python - 如何在 Django 中按类别筛选产品?
- vba - 刷新子表单
- django-rest-framework - 从 Django REST 框架中的访问令牌获取用户详细信息 - 简单 JWT
- node.js - 当我使用 Model.find({}) 查找所有带有 mongoose 的文档时,我可以取回格式化的 json 响应吗?
- r - 保存文件并在绘图中显示
- r - 如何在R中的单独数据框中输出两个不同数据框的列