【问题标题】:Understanding useState from a jQuery perspective从 jQuery 的角度理解 useState
【发布时间】:2022-02-24 07:09:41
【问题描述】:

据我了解,我们在 React 中将 useState 用于动态值,在 React 的情况下,它将是 const 而不是 var。

假设我想在单击按钮时将变量的值从 false 更改为 true,并且我想告诉用户是否单击了按钮。这是我在 jQuery 中编写它的方式: page.js

//Define variable 
var buttonClicked = false;
//Define function for button click
$('button').click(function() {
  //redefine variable 
  buttonClicked = true;
  //Show button status
  $('.button').text('Button has been clicked!')
});

page.html

<button>Click me</button>
<div class="button-status">Button has not been clicked</div>

如何在 React 中编写这个函数?

【问题讨论】:

  • “我将如何在 React 中编写这个函数?”...你尝试了什么? StackOverflow 不是代码编写服务

标签: jquery reactjs use-state


【解决方案1】:

Page.js

import { useEffect, useState } from 'react';

const Page = () => {
  //create the const for buttonClicked for outputing the value and setClickStatus for the function that will return the value of buttonClicked. 
  const [buttonClicked,setClickStatus] = useState(false);
  
  return (
    <div>
      {/* add the setClickStatus on button click so that when the button is clicked the value of buttonClicked is true. */}
      <button onClick={() => setClickStatus(true)}>Click me</button>
      {/* Display the a message based on the buttonClicked value. 'Button is clicked' for true and 'Button has not been clicked' for false. */}  
      <div className="button-status">{ buttonClicked ? 'Button is clicked' : 'Button has not been clicked' }</div>
    </div>
  );

}

export default Page;

一些背景知识:我已经完成了一堆 React 教程,但解释往往使用很多行话,所以我必须查找每个单词的含义,所以这些概念会消失。而在我的 cmets 中,我试图尽可能清楚地解释正在发生的事情。请记住,我们是人类,我们可以接受语言的细微差别而不会抛出语法错误。

【讨论】:

  • 我注意到 react 的一件事是它的代码比 jQuery 多得多。 jQuery 编写起来非常简单,并且可以用简单的语法完成您需要做的事情,而且只有一些奇怪的事情,比如在 setTimeout 中使用 $(this)。 React 的一大优势是我可以将所有的 HTML、JS 和 CSS 添加到一个地方,因此更容易避免语法错误。
猜你喜欢
  • 2014-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
  • 2014-11-24
相关资源
最近更新 更多