![](/img/trans.png)
[英]How to pass updated array object to parent component from child component in reactJs
[英]How to pass an object to a custom child component in ReactJS using Typescript?
我想通过useEffect()
在 App 的根组件中获取数据(并将它们设置为状态),然后将 state 传递给我的自定义组件。 我可以用 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
对我来说,看起来我有一个 object 类型的人我无法分配给另一种类型的人......
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;
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 视频或以前的帖子...基于这些问题( 这里和这里)我想我需要声明我的组件的接口?
如果是这样:
非常感谢任何帮助。 谢谢!
问题是这个
const Profile: React.FC<Person>
应该是这个
const Profile: React.FC<{ obj: Person }>
也就是说, props
不是Person
类型,您在Profile
中有一个obj
prop 是Person
类型。
React.FC<T>
中的类型参数T
需要是所有自定义道具的形状,在内置的 React 道具(即children
)之上 - 所以基本上是一个带有字段的 object 。
例如,如果你有另一个应该是数字的道具foo
,它将是React.FC<{ obj: Person, foo: number }>
等。
你传递的道具形状实际上是
export interface Person {
obj: {
name: string;
email: string;
dob: string;
address: string;
number: string;
userName: string;
pssw: string;
}
};
但你宣布
export interface Person {
name: string;
email: string;
dob: string;
address: string;
number: string;
userName: string;
pssw: string;
};
既然我看到你喜欢学习和尝试,我会让你弄清楚在哪里可以进行调整,如果不能的话。 让我知道,我会添加更多详细信息。
你可以这样做:
// Here you create an interface for Profile component that receives an "obj" prop of Person type.
interface ProfileProps {
obj: Person;
}
const Profile: React.FC<ProfileProps> = (props) => {
console.log(props.obj);
return (
....
现在你会好起来的,因为当你在 App 组件中设置 Profile 标签时,你传递了 obj 属性:
<Profile obj={profile} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.