简体   繁体   中英

How to use new Feature Hooks in React?

I just read about the react's new feature hooks. Read about hooks but i can't able to use it. it gives me error.

I am currently using version 16.6.0

Finally i got Understand the hooks.

import React, {useState} from 'react';

const Fun = () => {
    const [count, setCount] = useState(0);

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

 export default Fun;

I imported as Fun and used as in my app.js file

The mistake i made is i did't install React v16.7.0-alpha so i installed using npm add react@next react-dom@next.

Thank you

EDIT:

Hooks are released as a part of version 16.8.0 and you can use it by installing React and React-dom 16.8.0

run

yarn install react@16.8.0 react-dom@16.8.0

to install. In order to upgrade react to latest version

yarn upgrade react react-dom

Hooks aren't present in version 16.6.0, but are a proposal for version 16.7.0. You can however use 16.7.0-alpha.0 alpha version of React to test them

In order to use this install the above version using

yarn add react@next react-dom@next

Make sure that you install both react and react-dom or else your would get warning like

TypeError: Object(…) is not a function” error when trying to use react hooks (alpha)

You have to be using version 16.7.0-alpha.0 (or higher) for react and react-dom to try out hooks. Use the following snippet for reference:

 function App() { const [name, setName] = React.useState('Mary'); return ( <div>Name: <input value={name} onChange={(event) => setName(event.target.value)} /> <p>{name}</p> </div> ); } ReactDOM.render(<App />, document.querySelector('#app')); 
 <script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script> <div id="app"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM