React Native:创建道具和状态

时间:2017-11-20 20:05:57

标签: reactjs react-native

一个菜鸟问题。

我有这个组件包含道具和状态。

有人可以告诉我如何为基于类的组件定义道具吗?

我收到以下错误

"ReferenceError: Can't find variable: logstringdate"

这是我的代码

import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';



export default class Logitem extends Component {

  constructor(props)  {
    super(props);
    const { logstringdate, bmi, weight, logdate } = props;
  }


onWeightClick = () => {
  console.log('The element ==> '+logdate);
}


render() {

  return (
    <View style={styles.containerStyle}>
              <View style={styles.headerContentStyle}>
                    <Text>{logstringdate}</Text>
                    <Text>{bmi}</Text>
              </View>
              <View style={styles.thumbnailContainerStyle}>
                    <Text onPress={this.onWeightClick}>{weight}</Text>
              </View>
    </View>
  );

}
};

const styles = {
  containerStyle: {
    borderWidth: 1,
    borderRadius: 2,
    borderColor: '#ddd',
    borderBottomWidth: 0,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2},
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 1,
    marginLeft: 5,
    marginRight: 5,
    marginTop:10,
  },
  thumbnailContainerStyle: {
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: 10,
    marginRight: 10,
    flexDirection: 'row'

  },
  headerContentStyle: {
    flexDirection: 'column',
    justifyContent: 'space-around'
  },
};

我想将logstringdate,bmi,weight,logdate作为道具。

有人可以告诉我这里有什么问题吗?

1 个答案:

答案 0 :(得分:1)

class方法中,您应该使用this关键字引用属性:

const { logstringdate, bmi, weight, logdate } = this.props;  

此外,您在constructor块范围内(您实际上并未使用它们)声明变量,但在render方法中,这是一个单独的块上下文,您没有声明变量:

const { logstringdate } = this.props;  

或者:

<Text>{this.props.logstringdate}</Text>