ProfilePageFunction.js

  1. import React from 'react';
  2. function ProfilePage(props) {
  3. const showMessage = () => {
  4. alert('Followed ' + props.user);
  5. };
  6. const handleClick = () => {
  7. setTimeout(showMessage, 3000);
  8. };
  9. return (
  10. <button onClick={handleClick}>Follow</button>
  11. );
  12. }
  13. export default ProfilePage;

函数式组件2

  1. const App = () => {
  2. const [c1, setC1] = useState(0);
  3. const [c2, setC2] = useState(0);
  4. const [c3, setC3] = useState(0);
  5. const increment = c => c + 1
  6. // 只有 useCallback 对应的 c1 或 c2 的值改变时,才会返回新的函数
  7. const increment1 = useCallback(() => setC1(increment), [c1]);
  8. const increment2 = useCallback(() => setC2(increment), [c2]);
  9. return (<View>
  10. <Text> Counter 1 is {c1} </Text>
  11. <Text> Counter 2 is {c2} </Text>
  12. <Text> Counter 3 is {c3} </Text>
  13. <View>
  14. <Button onClick={increment1}>Increment Counter 1</Button>
  15. <Button onClick={increment2}>Increment Counter 2</Button>
  16. <Button onClick={() => setC3(increment)}>Increment Counter 3</Button>
  17. </View>
  18. </View>)
  19. }

ProfilePageClass.js

  1. import React from 'react';
  2. class ProfilePage extends React.Component {
  3. showMessage = () => {
  4. alert('Followed ' + this.props.user);
  5. };
  6. handleClick = () => {
  7. setTimeout(this.showMessage, 3000);
  8. };
  9. render() {
  10. return <button onClick={this.handleClick}>Follow</button>;
  11. }
  12. }
  13. export default ProfilePage;

参考

https://juejin.im/post/5ceb36dd51882530be7b1585