【发布时间】:2020-12-11 07:01:41
【问题描述】:
目标
我想通过useEffect() 获取应用程序根组件中的数据(并将它们设置为状态),然后将状态传递给我的自定义组件。我可以用 JS 做到这一点,但同样的步骤不适用于 Typescript。
我的错误信息如下:
Type '{ obj: Person; }' is not assignable to type 'IntrinsicAttributes
& Person & { children?: ReactNode; }'. Property 'obj' does not exist
on type 'IntrinsicAttributes & Person & { children?: ReactNode; }'.TS2322
对我来说,看起来我有一个 Person 类型的对象,我无法分配给其他类型的 Person...
App.tsx
import React, { useState, useEffect } from 'react';
import Profile from '../Profile';
export interface Person {
name: string;
email: string;
dob: string;
address: string;
number: string;
userName: string;
pssw: string;
};
const initPerson: Person = {
name: "",
email: "",
dob: "",
address: "",
number: "",
userName: "",
pssw: ""
};
const App: React.FC = () => {
const [ profile, setProfile ] = useState<Person>(initPerson)
useEffect(() => {
// logic for fetching data and setting the state
}, []);
return (
<div id="app">
<h1>Random user generator</h1>
<div id="content">
<Profile obj={profile} />
</div>
);
}
export default App;
Person.tsx
import React from 'react';
import { Person } from './app/App'
const Profile: React.FC<Person> = (props) => {
return (
<div id="Card">
{/* photo */}
<div id="photo"><img src="" alt="profile" /></div>
{/* name */}
<div id="name"></div>
{/* email */}
<div id="email"></div>
{/* dob */}
<div id="dob"></div>
{/* adress */}
<div id="address"></div>
{/* number */}
<div id="number"></div>
{/* pssw */}
<div id="password"></div>
</div>
);
}
export default Profile;
我在这里找不到任何相关的 YT 视频或以前的帖子...基于这些问题(here 和 here)我想我需要声明我的组件的接口?
如果是这样:
- 在哪里?
- 如果我已经为要传递给组件的 Person 定义了接口,为什么还需要声明组件的接口?
- 声明应该是什么样的?
- 错误告诉我什么?
- 我应该如何正确地将数据传递给子组件? (以及从孩子到父母)
- 还有什么我应该知道的吗?
非常感谢任何帮助。谢谢!
【问题讨论】:
标签: javascript reactjs typescript react-component