在 React JS 中的变量类型函数中切换文本 [英] Toggle text within a variable type function in React JS

查看:25
本文介绍了在 React JS 中的变量类型函数中切换文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个函数:

import React from "react";

const Test = () => {
  return (
    <React.Fragment>
      <h1>Hello World</h1>
    </React.Fragment>
  );
};

export default Test;

我想用一个按钮打开和关闭 Hello World 文本.我将如何实现这一目标?我看过:

I want to toggle the Hello World text on and off with a button. How would I achieve this? I have looked at:

  1. React.js 切换按钮的工作原理

地图函数中的 React js onclick 切换类

他们都没有真正的帮助.他们使用了 this.state,我遇到了类型错误,然后我开始怀疑是否应该使用变量类型函数,因为我看过的所有教程都使用 代替.所以我的问题是,如何在可变类型函数中实现切换文本?

And none of them helped really. They used this.state, to which I got a type error, and then I started wondering if I should use a variable type function or not, as all the tutorials I've looked at use class instead. So my question is, how would I achieve toggling text in a variable type function?

如果您需要更多信息,或者如果我的问题措辞不当,请告诉我.很感谢任何形式的帮助.谢谢!

If you need anymore information, or if my question was poorly phrased, please tell me. Any help is very much appreciated. Thank you!

推荐答案

this.state 在您的功能组件中没有任何意义.

this.state has no meaning in your functional component.

相反,您可以这样做:

import React, { useState } from "react";

const Test = () => {
  const [showText, setShowText] = useState(false);
  return (
    <React.Fragment>
      {showText && <h1>Hello World</h1>}
      <button onClick={() => setShowText(!showText)}>Toggle</button>
    </React.Fragment>
  );
};

我们使用 useState 来创建一些状态并将其初始值设置为 false(即不应显示文本).

We use useState to create some state and set its initial value to false (i.e. The text should not be shown).

然后在按钮的 onClick 属性中,我们可以通过设置 showTexttruefalse 之间切换状态值code> 并使用它来有条件地呈现文本.

Then inside the onClick property of our button we can toggle the state value between true and false by setting showText and use this to conditionally render the text.

沙盒示例

这篇关于在 React JS 中的变量类型函数中切换文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆