我目前正在学习React中的钩子概念,并试图理解下面的例子。
import { 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>
);
}
上面的示例增加了处理程序函数参数本身的计数器。如果我想修改事件处理函数内的计数值怎么办
考虑下面的例子:
setCount = () => {
//how can I modify count value here. Not sure if I can use setState to modify its value
//also I want to modify other state values as well here. How can I do that
}
<button onClick={() => setCount()}>
Click me
</button>
React useState是React钩子,允许你在功能组件中管理状态。
例如:
import React, { useState } from 'react'
const Example = () => {
// create the "counter" state
const [count, setCount] = useState(0)
return (
<div>
<p>Button clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Count + 1
</button>
</div>
)
}
export default Example
使用useState,您可以轻松地创建有状态的功能组件。
旧的等效方法,使用Component类和setState类组件是:
import React, { Component } from 'react'
class Example extends Component {
constructor(props) {
super(props)
this.state = { count: 0 }
}
render() {
const { count } = this.state
return (
<div>
<p>Button clicked {count} times</p>
<button onClick={() => this.setState({ count: count + 1 })}>
Count + 1
</button>
</div>
)
}
}
export default Example
来源:
React useState Hook:什么是新的和使用它
链接:
React Hooks文档
useState是一个钩子,允许您向功能组件添加状态。它接受一个作为状态属性初始值的参数,并返回状态属性的当前值和一个能够更新状态属性的方法。
下面是一个简单的例子:
import React, { useState } from react
function HookCounter {
const [count, setCount]= useState(0)
return(
<div>
<button onClick{( ) => setCount(count+1)}> count{count}</button>
</div>
)
}
useState接受状态变量的初始值,在本例中为零,并返回一对值。状态的当前值被称为count,可以更新状态变量的方法被称为setCount。