如何在 Next.js 中管理组件状态

Xen*_*non 3 reactjs next.js

我正在制作一个组件,它将跟踪用户在输入中输入的文本,并在其更改时调用一个方法。我计划将输入的值存储在状态中,但this在 /components 中的 js 文件中未定义。这是我尝试过的

export default function TalentSearch() {
  this.state = 'val';

  return (
    <div>
      <button onClick={clicked}>click me</button>
      <input type="text" name="search" />
      <div>
        <p>{this.state.value}</p>
      </div>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

感谢您提前的帮助

小智 5

您在这里定义的是一个功能组件。只有类组件可以使用this. 因此,您可以更改类组件的内容,也可以使用useState这样的钩子在功能组件中简单地拥有状态:

import { useState } from 'react'; 

export default function TalentSearch() {
  const [value, setValue] = useState("value")

  return (
    <div>
      <button onClick={clicked}>click me</button>
      <input type="text" name="search" />
      <div>
        <p>{value}</p>
      </div>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

一些笔记

  • 只需调用value组件内的任何位置即可获取当前状态,如果您想更改它,请使用设置状态函数,如下所示:setValue(new state)