将函数作为 props 传递会在 React Native 中生成错误(onPress 不是函数,'onPress' 是 Object 的实例)



我试图从子组件触发父组件中的一些动作,我正在使用props。子的一个道具是一个函数,当按钮被按下时,它更新父的状态,这应该导致父的重新渲染,但事实并非如此,而是我得到这个错误:TypeError: onPress is not a function. (In 'onPress(event)', 'onPress' is an instance of Object)。我已经使用了功能作为道具,并在React中多次更新状态,但在React Native中,我似乎不明白是什么导致了这个问题,以及如何从我在网上找到的信息中解决这个问题。

子组件:

import * as React from 'react';
import {Avatar, Button, Card, Title, Paragraph } from 'react-native-paper';
const Photo:React.FC<{url:string, camera:string, handleClick:()=>void}> = ({url, camera}:{url:string, camera:string}, handleClick:()=>void) => (
<Card >
<Card.Content >
<Paragraph style={{color:'#6200ee'}}>{camera}</Paragraph>
</Card.Content>
<Card.Cover source={{ uri: url }} />
<Card.Actions>
<Button onPress={handleClick} mode='contained'>more</Button>
</Card.Actions>
</Card>
);
export default Photo;
父组件:

import React, {useContext, useEffect, forwardRef, useState, Ref, useImperativeHandle, useRef} from 'react'
import { View, Text, ScrollView, StyleSheet } from 'react-native'
import { ActivityIndicator} from 'react-native-paper';
import {theContext}  from '../utils/ContextPlaceholder'
import getPhotos from '../utils/getPhotos'
import Photo from './Photo'
import axios from 'axios';
import {PhotosViewV2} from './PhotosViewV2'
import ImageViewer from 'react-native-image-zoom-viewer';
interface RefObject {
getData: () => void
}

export const PhotosView = forwardRef((props, ref: Ref<RefObject>)=> {
const [photos, setPhotos]=useState<any[]>([])
const[clicked, setClicked]=useState(false)
const context=useContext(theContext)
const{rover, camera, year,month,day} =context
useImperativeHandle(ref, () => ({getData}));
async function getData() {
const photos=await getPhotos(1,rover, camera, year,month,day)
setPhotos(photos)
}
return(
<View>
<ScrollView>
{photos.map(({cam, url},idx)=>{
return <Photo handleClick={()=>setClicked(true)} camera={cam} key={idx} url={url}/>
})}

</ScrollView>
<PhotosViewV2 clickedFromOutside={clicked} data={photos}/>
</View>
);
});

问题是这里的({url, camera}:{url:string, camera:string}, handleClick:()=>void)你从第一个参数得到urlcamera,即props,从第二个参数得到handleClick,即forwardRef,这确实是一个对象。你需要像这样重写它:

({url, camera, handleClick}:{url:string, camera:string, handleClick:()=>void})

最新更新