【发布时间】:2021-10-15 06:13:42
【问题描述】:
我正在尝试从子组件触发父组件中的某些操作,为此我正在使用道具。孩子的道具之一是当按下按钮时更新父母状态的函数,这应该导致父母重新渲染但事实并非如此,而是出现此错误: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>
);
});
【问题讨论】:
标签: typescript react-native react-props