开始创建一个最简单的组件, 我们定义一个接口
import React from 'react'
interface IHelloProps {
message: string
}
const Hello = (props: IHelloProps) => {
return <h2>{props.message}</h2>
}
export default Hello;
再一次去优化我们的组件,现在我们的组件的porps过于单一,我们传进来是什么就是什么,我们可以让它拥有一些react的特性。例如给props加上children参数
import React from 'react'
interface IHelloProps {
message?: string // ? 代表可传可不传
}
const Hello: React.FunctionComponent<IHelloProps> = (props) => {
return <h2>{props.children}</h2>
}
// 简写
const Hello: React.FC<IHelloProps> = (props) => {
return <h2>{props.children}</h2>
}
Hello.defaultProps = {
message: 'Hellow World',
}
export default Hello;
// 我们就可以这样去使用我们的组件
<Hello/>Hello World</Hello>