类组件是发展时间最长、接受度最广的,但是Hooks才是未来。

简单例子

src/components/HelloHooks.tsx

  1. import React, { useState, useEffect } from 'react';
  2. interface Greeting {
  3. firstName: string,
  4. lastName: string,
  5. name: string,
  6. }
  7. const HelloHooks = (props: Greeting) => {
  8. const [count, setCount] = useState(0);
  9. const [text, setText] = useState<string | null>(null);
  10. useEffect(() => {
  11. if(count > 5) setText('休息一下')
  12. })
  13. return (
  14. <div>
  15. <p>你点击了{count}次,{text}</p>
  16. <button onClick={() => {setCount(count + 1)}}>hello, {props.name}</button>
  17. </div>
  18. )
  19. }
  20. HelloHooks.defaultProps = {
  21. firstName: '',
  22. lastName: '',
  23. }
  24. export default HelloHooks;

src/index.tsx

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import HelloHooks from './components/HelloHooks';
  4. ReactDOM.render(<HelloHooks name='yefei' />, document.getElementById('app'));

这里出现了一个知识点 defaultProps,不进行设置的话传入的{name} 不满足 Greeting 就会报错。

参考提交:296e907