首页 > 解决方案 > 如何在反应离子中将道具从一个组件传递到另一个组件

问题描述

我将道具从Login组件传递到StoreView组件。当我通过道具然后收到打字稿错误。

打字稿错误类型'{数据:调度>; }' 不可分配给类型“IntrinsicAttributes”。类型“IntrinsicAttributes”上不存在属性“数据”。

我的登录组件

import React, { useState } from "react";
//more imports

const Login: React.FC = () => {
  //some states
  const [storeData, setStoreData] = useState([]);

  const loginUser = (event: any) => {
    event.preventDefault();
    const loginApi = LoginAPI.userLogin(userEmail, password);
    loginApi
      .then((res) => {
        if (res) {
          setStoreData(res.store_id)
        }
        else {
          alert('invalid user')
        }
      })
  };

  return (
    <IonPage>
      <IonContent>
      <div className="login-container">    
        <div className="login-form-wrapper">
          Login please
          <form className="login-form" onSubmit={loginUser}>
            //my form data
          </form>
        </div>
      </div>
      </IonContent>
      <StoreView 
       //here i am getting error
       data = {setStoreData}
      />
    </IonPage>
  );
};
export default Login;

我想将我的道具传递给StoreView组件,但在登录组件中出现错误。

我的StoreView组件。

import React, { useEffect, useState } from 'react';
//more imports

const StoreView: React.FC = () => {
    return (
      <IonContent>
          //here i want to my props data
       </IonContent>
    ); 
}  

export default StoreView;

标签: javascriptreactjstypescriptionic-framework

解决方案


您必须为 StoreView 组件定义道具类型。

type Props = {
    // do not use `any`, I don't know the structure of your data
    // you should create an interface suitable for the type of data you want
    data: any[];
}

const StoreView = ({ data }: Props) => {
    return (
      <IonContent>
          // do something with data
       </IonContent>
    ); 
}

然后你可以像在你的例子中一样使用它(但你可能应该通过storeData那里,而不是setStoreData)。


推荐阅读