我有两个组件。一个是 App.tsx 文件,在其中,我调用 API 来获取一些数据。我获取该数据并尝试将其传递下去,但出现错误 Type 'Element' has no properties in common with type 'Props'. TS2559
Props 是我为 App 组件制作的界面名称。另一个组件只是想要接收 props 的子组件。
import './App.css';
import * as React from "react";
import {useState, useEffect} from "react";
import UsersList from "./components/UsersList";
import Form from "./components/Form"
interface Props {
userList?: any
}
const App = (): Props => {
const [users, setUsers] = useState([])
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/todos")
.then(res => res.json())
.then(usersList => {
setUsers(usersList)
})
.catch(err => {
throw new Error(err);
})
}, [])
return (
<div className="App">
<Form />
<UsersList userList={users}></UsersList>
</div>
);
}
export default App;
答案 0 :(得分:1)
如果您在 () ((): Props
) 之后设置类型,您就是在定义返回类型。如果要设置参数的类型,需要在()((props: Props)
)内定义。
试试这个:
import './App.css';
import * as React from "react";
import {useState, useEffect} from "react";
import UsersList from "./components/UsersList";
import Form from "./components/Form"
interface Props {
userList?: any
}
const App = ({userList}: Props) => {
const [users, setUsers] = useState([])
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/todos")
.then(res => res.json())
.then(usersList => {
setUsers(usersList)
})
.catch(err => {
throw new Error(err);
})
}, [])
return (
<div className="App">
<Form />
<UsersList userList={users}></UsersList>
</div>
);
}
export default App;
答案 1 :(得分:1)
您似乎放错了 Props
类型。如示例所示,您是说 App
函数应返回 Props
。
你可以这样定义:
const App = (props: Props) => {
或者您可以使用 React
提供的类型:
const App: React.FC<Props> = (props) => {