类组件是发展时间最长、接受度最广的,但是Hooks才是未来。
简单例子
src/components/HelloHooks.tsx
import React, { useState, useEffect } from 'react';
interface Greeting {
firstName: string,
lastName: string,
name: string,
}
const HelloHooks = (props: Greeting) => {
const [count, setCount] = useState(0);
const [text, setText] = useState<string | null>(null);
useEffect(() => {
if(count > 5) setText('休息一下')
})
return (
<div>
<p>你点击了{count}次,{text}</p>
<button onClick={() => {setCount(count + 1)}}>hello, {props.name}</button>
</div>
)
}
HelloHooks.defaultProps = {
firstName: '',
lastName: '',
}
export default HelloHooks;
src/index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import HelloHooks from './components/HelloHooks';
ReactDOM.render(<HelloHooks name='yefei' />, document.getElementById('app'));
这里出现了一个知识点 defaultProps
,不进行设置的话传入的{name} 不满足 Greeting 就会报错。
参考提交:296e907