App.tsx
import { useCallback, useState } from 'react'
import Chat from './components/Chat'
import ContactList from './components/ContactList'
import './App.css'
import type { Contact } from './types.ts'
function App() {
const contactList = [
{name: "liming", email: "123@gmail.com", id: 1},
{name: "lihong", email: "456@gmail.com", id: 2},
{name: "zhangsan", email: "789@gmail.com",id: 3}
]
const [to, setTo] = useState(contactList[0])
const changeContact = useCallback((contact: Contact) => {
setTo(contact)
},[])
return (
<>
<div>
<ContactList
contactList={contactList}
onChange={changeContact}
/>
<Chat key={to.id} contact={to}/>
</div>
</>
)
}
export default App
ContactList.tsx
import {useState} from 'react'
import type { Contact, ContactListProp } from '../types'
export default function ContactList({contactList, onChange}: ContactListProp) {
return (
<section>
<ul>
{
contactList.map((contact: Contact) => (
<li
key={contact.id}
onClick={() => onChange(contact)}
>
{contact.name}
</li>
))
}
</ul>
</section>
)
}
Chat.tsx
import {useState} from 'react'
import type {Contact} from '../types'
export default function Chat ({contact}: {contact: Contact}) {
const [text, setText] = useState('')
return (
<section>
<textarea value={text} onChange={e => setText(e.target.value)}></textarea>
<p>发送给{contact.email}</p>
</section>
)
}
Types.ts
export interface Contact {
id: number;
name: string;
email: string;
}
export interface ContactListProp {
contactList: Contact[];
onChange: (contact:Contact) => void
}
总结:
- Type.ts的导出及App.tsx的导入ts
- 注意useState的初始值
- jsx放在循环中如何写
- Props传参注意
- ts的使用方法