【问题标题】:passing function as props generates an error in React Native(onPress is not a function, 'onPress' is an instance of Object)将函数作为道具传递会在 React Native 中产生错误(onPress 不是函数,'onPress' 是 Object 的实例)
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 哇,我怎么没注意到这一点,谢谢!
    猜你喜欢
    • 2018-05-07
    • 2017-12-06
    • 2020-11-24
    • 1970-01-01
    • 2023-01-21
    • 2023-03-28
    • 2019-12-01
    • 2021-09-15
    相关资源
    最近更新 更多