is it possible to React.useState(() => {}) in React?

后端 未结 2 709
一向
一向 2021-02-02 09:03

is it possible to use a function as my React Component\'s state ?

example code here:

// typescript 
type OoopsFunction = () => void;

exp         


        
2条回答
  •  时光说笑
    2021-02-02 09:55

    It is possible to set a function in state using hooks, but because state can be initialized and updated with a function that returns the initial state or the updated state, you need to supply a function that in turn returns the function you want to put in state.

    const { useState } = React;
    
    function App() {
      const [ooops, setOoops] = useState(() => () => console.log("default ooops"));
    
      return (
        
    ); } ReactDOM.render(, document.getElementById("root"));
    
    
    
    

提交回复
热议问题