【问题标题】:Error: this.props.header is not a function when using StackNavigator错误:使用 StackNavigator 时 this.props.header 不是函数
【发布时间】:2018-04-09 13:34:02
【问题描述】:

我的 react-navigation StackNavigator 中有一个屏幕,如下所示:

import React from 'react';
import { FlatList, ScrollView, StyleSheet, Text, View } from 'react-native';
import { List, ListItem } from 'react-native-elements';
import Accordion from '@ercpereda/react-native-accordion';

export default class PassportScreen extends React.Component {
    static navigationOptions = {
        title: 'Passport Recovery',
    };

    constructor(props) {
        super(props);
        this.renderItem = this.renderItem.bind(this);
    }

    renderItem(item) {
        return (
            <View>
                <Accordion
                    header={item.item.key}
                    content={item.item.content}
                />
            </View>
        )
    }

    render() {
        const instructions = [
            {
                key: <Text>1. Fill out a passport application form</Text>,
                content: <Text>Content</Text>
            },
            {
                key: <Text>2. Fill out a lost/missing passport statement</Text>,
                content: <Text>Content</Text>
            },
            ///...etc
        ];

        return (
            <ScrollView>
                <FlatList
                    data={instructions}
                    renderItem={this.renderItem}
                />
            </ScrollView>
        )
    }
}

module.exports = PassportScreen;

但是,当我单击以从另一个屏幕导航到此屏幕时,我收到此错误:TypeError: this.props.header is not a function. (In 'this.props.header({ isOpen: this.state.is_visible })', 'this.props.header' is an instance of Object)。 我看过的其他类似错误的问题提到了将道具传递给构造函数并需要传递this.renderItem而不是this.renderItem(),这两个我都已经完成了,所以我想知道问题是否来自事实该屏幕位于 StackNavigator 内,并通过单击 ListItem 导航到。我的直觉正确吗?如果是这样,我该如何解决这个问题?

【问题讨论】:

    标签: javascript reactjs react-native react-props stack-navigator


    【解决方案1】:

    似乎 header 属性接受一个函数,而不仅仅是一个像 content 那样的组件。

    【讨论】:

      【解决方案2】:

      现在您直接将object 传递给标头prop,因此它不会接受回调函数。

      您可以尝试以下方法以将回调传递给标头。

      PassportScreen.js

      customFunc = (callback) => {
        console.log(callback)
      }
      
      renderItem = (item) => { // Useful to bind `this` 
              return (
                  <View>
                      <Accordion
                          header={this.customFunc}
                          content={item.item.content}
                      />
                  </View>
              )
          }
      

      ChildComponent.js

      this.props.header('I'm setting the callback here')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-01
        • 1970-01-01
        • 2021-05-24
        • 1970-01-01
        • 1970-01-01
        • 2018-06-01
        • 2020-08-05
        • 2017-04-27
        相关资源
        最近更新 更多