【问题标题】:Testing this.props.navigation测试 this.props.navigation
【发布时间】:2018-11-12 03:58:36
【问题描述】:
import React from 'react';
import ListElements from '../Components/ListElements';
class HospitalsScreen extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      Hospitals: ['Hospital de Base','Hospital Regional de Taguatinga','Hospital da Ceilandia','Clínica']
    };
  }

  onPressItem() {
    this.props.navigation.navigate('sectors');
  }

  render() {
    return (
      <ListElements
      list = {this.state.Hospitals}
      title='Hospitais'
      onPress={this.onPressItem.bind(this)}
      />
    );
  }
}

export default HospitalsScreen;

我在 _onPress 函数中测试此屏幕时遇到了一些问题。 我没有找到任何解决问题的方法。

【问题讨论】:

  • 错误是什么?你能发布你用于导航的导航方法或库名称吗?
  • 我正在使用反应导航。问题是我找不到测试这个的方法,它总是给出错误“无法读取未定义的属性道具”
  • github.com/react-navigation/react-navigation/issues/2793。我认为这可能会对您有所帮助

标签: javascript react-native testing jestjs enzyme


【解决方案1】:

Javascript 中,函数内 this 的值取决于调用该函数的方式。

了解 this 绑定在 JavaScript here 中的工作原理

有几种方法可以实现它。使用它们,看看你是否在函数中得到 this 未定义。

一种是在构造函数中添加this.onPressItem = this.onPressItem.bind(this);

另一个是箭头函数

onPressItem= (event) => {this.props.navigation.navigate('sectors'); }

然后是onPress={this.onPressItem.bind(this)}

您可以找到更多详情here

也请看这篇文章Don't Use Bind When Passing Props

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-10
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    相关资源
    最近更新 更多