簡體   English   中英

箭頭 function 在 React-Native 中作為道具傳遞在傳遞給它的組件中未定義

[英]Arrow function passed as prop in React-Native is undefined in component it is passed to

我有一個容器組件:

import React, {FC, FormEvent, useState} from 'react';
// utils
import api from '../../api';
import {useAppSelector} from '../../store/hooks';
import CreateGroupPresentation from './CreateGroupPresentation';

interface Iprops {
  close: () => void;
}

interface IformState {
  title: string;
  upcs: string;
}

export interface IhandleChangeArgs {
  currentTarget: { value: string, id: string };
}

const CreateGroup: FC<Iprops> = ({close}) => {
  // get auth from redux
  const {token} = useAppSelector(state => state.auth);

  // local state for form
  const initialState: IformState = {title: '', upcs: ''};

  const [formState, setFormState] = useState(initialState);
  const {title, upcs} = formState;

  // handle change and submit for form
  const handleChange = (event: IhandleChangeArgs) => {
    const {id, value} = event.currentTarget;
    // prevents non-digits from being entered into the upc input
    if (id === 'upcs') {
      const numbers = /[\d\s]*/;
      const total = value.split('');
      const newChar = total[total.length - 1];
      if (!numbers.test(newChar)) return;
    }
    setFormState({...formState, [id]: value});
  };

  const handleSubmit = async (event: FormEvent) => {
    event.preventDefault();

    // converts the string from the upcs textarea to an array of numbers to send to the api
    const upcsToNumberArray: number[] = [];

    upcs
      .trim()
      .split('\n')
      .forEach(upc => upcsToNumberArray.push(parseInt(upc)));

    // eliminates duplicate UPCs
    const noDupes = [...new Set(upcsToNumberArray)];

    // send to api
    try {
      if (token) {
        const response = await api.createGroup(token, {
          title,
          upcs: noDupes,
        });
        console.log(response);
      }
    } catch (error: any) {
      console.log(error);
    }
  };

  const presentationProps = {handleSubmit, handleChange, title, upcs, close};

  return <CreateGroupPresentation {...presentationProps} />;
};

export default CreateGroup;

...將幾個道具作為presentationProps傳遞給一個展示組件:

import {Modal, View} from 'react-native';
import React, {FC, FormEvent} from 'react';
import styles from './CreateGroup.scss';
import MyButton from '../shared/MyButton/MyButton';
import LabelInput from '../shared/LabelInput/LabelInput';
import {IhandleChangeArgs} from './CreateGroup';

interface Iprops {
  handleSubmit: (event: FormEvent) => Promise<void>;
  handleChange: (event: IhandleChangeArgs) => void;
  title: string;
  upcs: string;
  close: () => void;
}

const CreateGroup: FC<Iprops> = ({handleChange, title, upcs, close}) => {
  return (
    <Modal animationType="slide" transparent>
      <View style={styles['modal-back']}>
        <View style={styles['modal-fore']}>
          <LabelInput
            label="Title"
            value={title}
            onChangeText={text =>
              handleChange({
                currentTarget: {
                  value: text.valueOf().toString(),
                  id: 'title',
                },
              })
            }
          />
          <LabelInput
            label="UPCs"
            value={upcs}
            multiline
            numberOfLines={12}
            onChangeText={text =>
              handleChange({
                currentTarget: {value: text.valueOf().toString(), id: 'upcs'},
              })
            }
          />
          <MyButton onPress={close} text="close" />
        </View>
      </View>
    </Modal>
  );
};

export default CreateGroup;

...但我收到一個渲染錯誤消息,handleChange 不是 function,實際上是未定義的。 如何正確通過 function? 有沒有一種方法可以在不改變 function 主體本身的情況下通過它? 我試圖在我的應用程序的 react-native 版本中保持容器組件與在 web 版本中相同。

注意:handleSubmit function 當前未在演示組件中使用,但接下來我將處理它。

我認為您忘記將第二個文件中的演示組件從CreateGroup重命名為CreateGroupPresentation 現在它在兩個文件中都稱為CreateGroup IE

 .... const CreateGroupPresentation: FC<Iprops> = ({ handleChange, title, upcs, close, }) => {... }; ... export default CreateGroupPresentation;

否則它看起來很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM