布尔类型的无效道具onPress

时间:2019-07-12 21:02:33

标签: react-native react-navigation expo

我正在制作本机博览会应用程序,我有一个问题。 我有2页。在page1.js中,我设置了page2.js的标题,与此有关。我有TouchableOpacity,可在其中导航到另一个页面,并在其中设置createStackNavigator选项的标题。在createStackNavigator选项中,我获取已发送的标题。它给我错误: 警告:道具类型失败:提供给onPress的类型boolean的道具TouchableOpacity无效,预期function。 还有一个: this.props.onPress不是函数

我做错了什么? 代码:

// page1.js
import React, { Component } from 'react';
import { StyleSheet, View, Button, Image, Text, TouchableOpacity, ScrollView, SafeAreaView, ActivityIndicator } from 'react-native';
import { Header } from 'react-navigation';
import { createStackNavigator, createAppContainer } from 'react-navigation';
import Icon from 'react-native-vector-icons/Ionicons'

import CoursesPlan from '../components/CoursesPlan'

const title = "a";

setTitle = (data) => {
title = data;
}

getTitle = () => {
return title;
}

class Page1 extends Component {
render() {
    return (
        <ScrollView>
            <View style={styles.MainContainer}>
                <TouchableOpacity
                    activeOpacity={.7}
                    onPress={() =>
                        setTitle("title"),
                        this.props.navigation.navigate('CourseOne', {
                        id: 1,
                    })}>
                    <CoursesPlan
                        number="1"
                        title="Что такое HTML?"/>
                </TouchableOpacity>
            </View>
        </ScrollView>
    );
}
}

export default createStackNavigator({
Main: {
    screen: Main,
    navigationOptions: {
        header: null,
    },
},
Page1: {
    screen: Page1,
    navigationOptions: ({ navigation }) => ({
        headerTitle: getTitle(),
        headerStyle: {
            elevation: 0,
            borderBottomWidth:1,
            borderBottomColor: "#dddddd",
        },
    }),
},},{
    initialRouteName: 'Main',
}
);

2 个答案:

答案 0 :(得分:2)

您没有为onPress提供函数,因为您没有将函数包装在括号内。

尝试使用您的onPress函数:

onPress={() => {
    setTitle("title");
    this.props.navigation.navigate('CourseOne', { id: 1,});
}}>

答案 1 :(得分:1)

首先,为什么要修改常量?

您不能像这样更改headerTitle。

请参阅反应导航文档

https://facebook.github.io/react-native/docs/navigation

https://reactnavigation.org/docs/en/headers.html

您不使用this.state,getTitle()不会重新渲染视图

https://facebook.github.io/react-native/docs/state

您使用this.props,但尚未编写构造函数。

What's the difference between "super()" and "super(props)" in React when using es6 classes?


class Test extends Component {

   constructor(props) { 
      super(props)
   }

   render() {
      return(<View />)
   }
 }