我从JavaScript帖子中获取了这段代码,我想在打字稿中使用它,但在const Contacts = ({contacts}) => {
我尝试{contacts: []}
失败。
联系人位于应用程序状态。
import React, { Component } from 'react';
import './App.css';
import Contacts from './components/contacts';
class App extends Component {
state = {
contacts: []
}
componentDidMount() {
fetch('http://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then((data) => {
this.setState({ contacts: data })
})
.catch(console.log)
}
render() {
return (
<Contacts contacts={this.state.contacts} />
)
}
}
export default App;
***contact.tsx ***
import React from 'react'
const Contacts = ({contacts}) => {Binding element 'contacts' implicitly has an 'any' type.ts(7031)
return (
<div>
<h1>Contact List</h1>
{contacts.map((contact: any) => (
<div>
<div>
<h5>{contact.name}</h5>
<h6>{contact.email}</h6>
<p>{contact.company.catchPhrase}</p>
</div>
</div>
))}
</div>
)
};
export default Contacts
我得到了错误:
绑定元素'contacts'隐式具有'any'类型。ts(7031)
答案 0 :(得分:0)
您必须告诉Contacts的道具是什么。您应该编写这样的接口:
interface ContactProps {
contacts: any[];
}
然后将此接口设置为Contacts组件,如下所示:
const Contacts: FC<ContactProps> = ({contacts}) => {...}
或
const Contacts = ({contacts}: ContactProps) => {...}
这将推断您传递给通讯录的道具的类型,并消除该错误。您还应该定义接口联系人并按以下方式编写:
interface Contact {
id: string;
name: string;
....
}
interface ContactProps {
contacts: Contact[];
}
现在,您可以使用正确的类型,并删除当前存在的任何类型。这也将帮助您捕获诸如拼写错误以及传递给子组件的内容之类的错误。 希望这可以帮助。 编码愉快。
答案 1 :(得分:0)
//it's ugly but it works
import React from 'react'
const Contacts = ({contacts}:any) => {
return (
<div>
<h1>Contact List</h1>
{contacts.map((contact: any) => (
<div>
<div>
<h5>{contact.name}</h5>
<h6>{contact.email}</h6>
<p>{contact.company.catchPhrase}</p>
</div>
</div>
))}
</div>
)
};
export default Contacts