我正在查看 https://codesandbox.io/s/new 中的默认演示 React 代码,结果如下:
import React from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
const App = () => <Hello name="CodeSandbox" />;
render(<App />, document.getElementById('root'));
这与我见过的许多其他示例不同,这些示例通常更类似于:
class Layout extends React.Component {
constructor(props) {
super(props);
this.state = {...};
}
render() {...}
}
由于codesandbox示例没有类或构造函数,因此我没有地方放置this.state
。那么我该如何以及在哪里添加一个状态呢?
最佳答案
从 React 16.8 开始,函数组件可以拥有状态。你不再需要上课了。
import React, { useState } from "react"; // need to import useState
function App() {
const [count, setCount] = useState(0); // initialize state
function changeState() {
setCount(count + 1); // change state
}
return (
<div className="App">
<h2>Count: {count}</h2>
<button onClick={changeState}>Change State</button>
</div>
);
}
完整示例 https://codesandbox.io/s/inspiring-newton-18bc9
useState() 是 Hook 的一个示例
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
关于reactjs - 当没有类或构造函数时,如何在 React 中设置状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47701662/