再聊react hook
React Hook是React函数式组件,它不仅仅有函数组件的特性,还带有React框架的特性。所以,官网文档多次强调:
只在 React 函数中调用 Hook
不要在普通的 JavaScript 函数中调用 Hook。你可以:
✅ 在 React 的函数组件中调用 Hook
✅ 在自定义 Hook 中调用其他 Hook
1. 那么 React 中 Function Component 与 Class Component 有何不同?
Class Component:
class ProfilePage extends React.Component {
  showMessage = () => {
    alert("Followed " + this.props.user);
  };
  handleClick = () => {
    setTimeout(this.showMessage, 3000);
  };
  render() {
    return ;
  }
}
Function Component:
function ProfilePage(props) {
  const showMessage = () => {
    alert("Followed " + props.user);
  };
  const handleClick = () => {
    setTimeout(showMessage, 3000);
  };
  return ;
}
如下父级组件的调用方式:
You clicked {count} times
You clicked {count} times
You clicked {count} times

发表评论 (审核通过后显示评论):