Luk*_*nat 2 javascript typescript reactjs react-component
我想通过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
Run Code Online (Sandbox Code Playgroud)
对我来说,看起来我有一个 Person 类型的对象,我无法分配给另一种类型的 Person...
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;
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
我在这里找不到任何相关的 YT 视频或之前的帖子...基于这些问题(此处和此处)我认为我需要声明我的组件的接口?
如果是这样:
非常感谢任何帮助。谢谢你!
问题是这个
const Profile: React.FC<Person>
Run Code Online (Sandbox Code Playgroud)
应该是这个
const Profile: React.FC<{ obj: Person }>
Run Code Online (Sandbox Code Playgroud)
也就是说,props不是类型为Person,你有一个类型为 的objprop 。ProfilePerson
T中的类型参数React.FC<T>需要是所有自定义道具的形状,位于内置的 React 道具之上(即children) - 所以基本上是一个带有字段的对象。
例如,如果您有另一个foo应该是数字的 prop,那么它将是React.FC<{ obj: Person, foo: number }>等等。
| 归档时间: |
|
| 查看次数: |
9942 次 |
| 最近记录: |