无法读取未定义的属性“ containerColor”(产生反应式自定义组件)

时间:2019-09-09 16:24:38

标签: javascript react-native custom-component

遇到此问题时,我正在尝试创建自己的react native组件。

  

无法读取未定义的属性'containerColor'

     

模块AppRegistry不是已注册的可调用模块(正在调用   runApplication)

我将此组件导入到我提供道具的app.js中。我不知道该怎么办。

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
};

出什么问题或缺少什么?预先谢谢你!

1 个答案:

答案 0 :(得分:0)

您正在尝试在上下文之外访问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
};