【问题标题】:React Native : creating both props and stateReact Native:同时创建 props 和 state
【发布时间】:2018-05-04 03:39:58
【问题描述】:

一个菜鸟问题。

我让这个组件同时包含道具和状态。

谁能告诉我如何为基于类的组件定义道具?

我收到以下错误

"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 作为 props。

谁能告诉我这里出了什么问题?

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

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

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

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

    const { logstringdate } = this.props;  
    

    或者:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      • 2020-05-25
      • 1970-01-01
      • 2022-06-12
      • 2018-12-04
      • 2019-02-02
      • 1970-01-01
      相关资源
      最近更新 更多