gpt4 book ai didi

javascript - 无法读取未定义的属性 'containerColor'(制作 react 性自定义组件)

转载 作者:行者123 更新时间:2023-11-30 06:12:55 25 4
gpt4 key购买 nike

当我遇到这个问题时,我正在尝试创建自己的 React Native 组件。

Cannot read property 'containerColor' of undefined

Module AppRegistry is not a registered callable module (calling runApplication)

我将这个组件导入到我的 app.js 中,我在其中提供 Prop 。我不知道还能做什么。

import React from "react";
import { View, Text, TouchableOpacity, StyleSheet } from "react-native";
import PropTypes from "prop-types";

export default class TreeViewBasic extends React.Component {
constructor(props) {
super();
}

render() {
<View
style={[
Styles.container,
this.props.selected ? Styles.oNBg : Styles.ofFBg
]}
>
<TouchableOpacity onPress={this.props.onPress}>
<View style={{ flex: 1 }}>
<Text style={this.props.selected ? Styles.oNColor : Styles.ofFColor}>
{this.props.name}
</Text>
</View>
</TouchableOpacity>
</View>;
}
}

export const Styles = StyleSheet.create({
container: {
flex: 4, //4 out of 5
elevation: 2,
alignSelf: "flex-end",
height: 40
},
ofFColor: {
color: "darkgray"
},
oNColor: {
color: "black"
},
ofFBg: {
backgroundColor: "gray"
},
oNBg: {
backgroundColor: this.props.containerColor
}
});

TreeViewBasic.defaultProps = {
selected: false,
containerColor: "white"
};

TreeViewBasic.propTypes = {
name: PropTypes.string.isRequired,
onPress: PropTypes.func,
selected: PropTypes.bool,
containerColor: PropTypes.string
};

有什么问题或不足?提前致谢!

最佳答案

您正试图在上下文之外访问 props。使用 StyleSheet.flatten 处理动态样式。

import React from "react";
import { View, Text, TouchableOpacity, StyleSheet } from "react-native";
import PropTypes from "prop-types";

export default class TreeViewBasic extends React.Component {
constructor(props) {
super();
}

render() {
const {containerColor} = this.props;
// dynamic style
const dynamicBG = StyleSheet.flatten([Styles.oNBg, {
backgroundColor: containerColor
}];

<View
style={[
Styles.container,
this.props.selected ? dynamicBG : Styles.ofFBg
]}
>
<TouchableOpacity onPress={this.props.onPress}>
<View style={{ flex: 1 }}>
<Text style={this.props.selected ? Styles.oNColor : Styles.ofFColor}>
{this.props.name}
</Text>
</View>
</TouchableOpacity>
</View>;
}
}

export const Styles = StyleSheet.create({
container: {
flex: 4, //4 out of 5
elevation: 2,
alignSelf: "flex-end",
height: 40
},
ofFColor: {
color: "darkgray"
},
oNColor: {
color: "black"
},
ofFBg: {
backgroundColor: "gray"
},
oNBg: {
backgroundColor: "transparent" // default color
}
});

TreeViewBasic.defaultProps = {
selected: false,
containerColor: "white"
};

TreeViewBasic.propTypes = {
name: PropTypes.string.isRequired,
onPress: PropTypes.func,
selected: PropTypes.bool,
containerColor: PropTypes.string
};

关于javascript - 无法读取未定义的属性 'containerColor'(制作 react 性自定义组件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57857839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com