功能组件中的共享钩子?

时间:2020-03-24 21:45:26

标签: reactjs

以下是example.js文档中hook中的React

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

此处,挂钩是在功能组件example中定义的。由于功能组件中可能有多个功能,我可以在组件中定义钩子并为组件中的所有功能共享状​​态吗?可能看起来像这样:

import React, { useState } from 'react';
const [count, setCount] = useState(0);  //<<==here define state `count` 

function doSomethingWithCount() {
  //do something with `count` //<<==here do something with `count`
}

export default function Example() {
  // Declare a new state variable, which we'll call "count"

  doSomethingWithCount();  //<<==here execute the function above

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

0 个答案:

没有答案