Skip to content

Instantly share code, notes, and snippets.

@wjx0820
Last active August 3, 2020 11:56
Show Gist options
  • Save wjx0820/e55ebcf1d4f83c9273cb94c27962dc83 to your computer and use it in GitHub Desktop.
Save wjx0820/e55ebcf1d4f83c9273cb94c27962dc83 to your computer and use it in GitHub Desktop.
使用React.PropsWithChildren或者 React.FC给带 children props 的组件 定义类型
// App.tsx
import { Button } from "./components/Button"
function App() {
return (
<div className="App">
<Button
onClick={(e) => {
e.preventDefault()
console.log(e)
}}
>
Hello World
</Button>
</div>
)
}
export default App
// Button.tsx
import React from "react"
type Props = {
onClick: (e: React.MouseEvent<HTMLButtonElement>) => void
}
export const Button = ({
onClick,
children,
}: React.PropsWithChildren<Props>) => {
return <button onClick={onClick}>{children}</button>
}
// or
// Use React.FC to type components
// That use children props
export const Button: React.FC<Props> = ({ onClick, children }) => {
return <button onClick={onClick}>{children}</button>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment