在上一节中,您已经学习了如何将React与较旧的钩子一起使用。在目前的版本里,hook已被引入React。
Hook是React 16.8中的新增功能。它们允许您使用状态,生命周期方法和其他React功能,而无需编写类组件。如果使用Hook,则在整个应用程序中只能有一个功能组件。有关更多详细说明,请查看 React中文社区。
不同的hooks已经写入React,包括基本的hooks跟额外的hooks
基础Hooks包括:
- useState
- useEffect
- useContext
使用钩子,我们可以访问状态而无需编写基于类的组件。让我们使用第8天用于基于类的组件的示例。
要使用钩子,首先我们应该从react导入useState钩子。useState是一个带有一个参数并返回当前状态的函数,该函数可让您对其进行更新。
// index.js
import React, { useState } from 'react'
import ReactDOM from 'react-dom'
const App = () => {
// Declaring new state variable
const [count, setCount] = useState(0)
return (
<div className='App'>
<h1>{count} </h1>
<button onClick={() => setCount(count + 1)}>Add One</button>
</div>
)
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
我们使用setCount来更新状态。初始状态值为0。
在上面的示例中,我们使用了增量方法。让我们也是一种递减方法。
// index.js
import React, { useState } from 'react'
import ReactDOM from 'react-dom'
const App = () => {
// Declaring new state variable
const [count, setCount] = useState(0)
return (
<div className='App'>
<h1>{count} </h1>
<button onClick={() => setCount(count + 1)}>Add One</button> <button onClick={() => setCount(count - 1)}>Minus One</button>
</div>
)
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
我们也可以编写单独的函数,而不是在大括号内编写函数。
// index.js
import React, { useState } from 'react'
import ReactDOM from 'react-dom'
const App = () => {
// Declaring new state variable
const [count, setCount] = useState(0)
const addOne = () => {
let value = count + 1
setCount(value)
}
const minusOne = () => {
let value = count - 1
setCount(value)
}
return (
<div className='App'>
<h1>{count} </h1>
<button onClick={addOne}>Add One</button> <button onClick={minusOne}>Minus One</button>
</div>
)
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
让我们做更多关于状态的例子,在下面的例子中,我们将开发一个显示狗或猫的小型应用程序。我们可以通过用cat设置初始状态开始,然后单击它会显示dog,或者。我们需要一种改变动物的方法。请参见下面的代码。如果要观看直播,请单击 这里.
// index.js
import React, { useState } from 'react'
import ReactDOM from 'react-dom'
const App = () => {
// declaring state
const url =
'https://www.smithsstationah.com/imagebank/eVetSites/Feline/01.jpg'
const [image, setImage] = useState(url)
const changeAnimal = () => {
let dogURL =
'https://static.onecms.io/wp-content/uploads/sites/12/2015/04/dogs-pembroke-welsh-corgi-400x400.jpg'
let catURL =
'https://www.smithsstationah.com/imagebank/eVetSites/Feline/01.jpg'
let result = image === catURL ? dogURL : catURL
setImage(result)
}
return (
<div className='App'>
<h1>30 Days Of React</h1>
<div className='animal'>
<img src={image} alt='animal' />
</div>
<button onClick={changeAnimal} class='btn btn-add'>
Change
</button>
</div>
)
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
现在,让我们放置到目前为止的所有代码,并在必要时使用useState挂钩实现状态。
// index.js
import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import asabenehImage from './images/asabeneh.jpg'
import './index.scss'
// Fuction to show month date year
const showDate = (time) => {
const months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
]
const month = months[time.getMonth()].slice(0, 3)
const year = time.getFullYear()
const date = time.getDate()
return ` ${month} ${date}, ${year}`
}
// User Card Component
const UserCard = ({ user: { firstName, lastName, image } }) => (
<div className='user-card'>
<img src={image} alt={firstName} />
<h2>
{firstName}
{lastName}
</h2>
</div>
)
// A button component
const Button = ({ text, onClick, style }) => (
<button style={style} onClick={onClick}>
{text}
</button>
)
// CSS styles in JavaScript Object
const buttonStyles = {
backgroundColor: '#61dbfb',
padding: 10,
border: 'none',
borderRadius: 5,
margin: 3,
cursor: 'pointer',
fontSize: 18,
color: 'white',
}
const Header = (props) => {
const {
welcome,
title,
subtitle,
author: { firstName, lastName },
date,
} = props.data
return (
<header style={props.styles}>
<div className='header-wrapper'>
<h1>{welcome}</h1>
<h2>{title}</h2>
<h3>{subtitle}</h3>
<p>
{firstName} {lastName}
</p>
<small>{date}</small>
</div>
</header>
)
}
const Count = ({ count, addOne, minusOne }) => (
<div>
<h1>{count} </h1>
<div>
<Button text='+1' onClick={addOne} style={buttonStyles} />
<Button text='-1' onClick={minusOne} style={buttonStyles} />
</div>
</div>
)
// TechList Component
const TechList = (props) => {
const { techs } = props
const techsFormatted = techs.map((tech) => <li key={tech}>{tech}</li>)
return techsFormatted
}
// Main Component
const Main = (props) => {
const {
techs,
user,
greetPeople,
handleTime,
changeBackground,
count,
addOne,
minusOne,
} = props
return (
<main>
<div className='main-wrapper'>
<p>Prerequisite to get started react.js:</p>
<ul>
<TechList techs={techs} />
</ul>
<UserCard user={user} />
<Button
text='Greet People'
onClick={greetPeople}
style={buttonStyles}
/>
<Button text='Show Time' onClick={handleTime} style={buttonStyles} />
<Button
text='Change Background'
onClick={changeBackground}
style={buttonStyles}
/>
<Count count={count} addOne={addOne} minusOne={minusOne} />
</div>
</main>
)
}
// Footer Component
const Footer = (props) => {
return (
<footer>
<div className='footer-wrapper'>
<p>Copyright {props.date.getFullYear()}</p>
</div>
</footer>
)
}
const App = (props) => {
const [count, setCount] = useState(0)
const [backgroundColor, setBackgroundColor] = useState('')
const showDate = (time) => {
const months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
]
const month = months[time.getMonth()].slice(0, 3)
const year = time.getFullYear()
const date = time.getDate()
return ` ${month} ${date}, ${year}`
}
const addOne = () => {
setCount(count + 1)
}
// method which subtract one to the state
const minusOne = () => {
setCount(count - 1)
}
const handleTime = () => {
alert(showDate(new Date()))
}
const greetPeople = () => {
alert('Welcome to 30 Days Of React Challenge, 2020')
}
const changeBackground = () => {}
const data = {
welcome: 'Welcome to 30 Days Of React',
title: 'Getting Started React',
subtitle: 'JavaScript Library',
author: {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
},
date: 'Oct 7, 2020',
}
const techs = ['HTML', 'CSS', 'JavaScript']
const user = { ...data.author, image: asabenehImage }
return (
<div className='app'>
{backgroundColor}
<Header data={data} />
<Main
user={user}
techs={techs}
handleTime={handleTime}
greetPeople={greetPeople}
changeBackground={changeBackground}
addOne={addOne}
minusOne={minusOne}
count={count}
/>
<Footer date={new Date()} />
</div>
)
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
用Hook函数来编写代码
🎉 CONGRATULATIONS ! 🎉