【问题标题】:How to change the button name in react?如何更改反应中的按钮名称?
【发布时间】:2020-09-30 20:12:14
【问题描述】:

我想要一个代码,当我单击按钮时更改按钮的名称,当我再次单击它时,它再次更改其以前的名称。

const [getName, setName] = useState(false);

        const handleNameChange = () => {
            setName(!getName); 
        }


    <button onClick={handleNameChange}>
           {getName ? 'Inactive' : 'active'}
       </button>

【问题讨论】:

  • 有什么问题?
  • 执行代码没有报错。可以使用条件 if 和 else 语句编写代码吗?我不知道,不幸的是
  • 究竟是什么错误?

标签: reactjs react-hooks react-functional-component


【解决方案1】:

你可以像这样在一行中完成。

import React, { useState } from "react";

function App() {
    const [isActive, setIsActive] = useState(false);

    return (
        <button onClick={() => setIsActive(!isActive)}>
            {isActive ? 'Active' : 'Inactive'}
        </button>
    );
}

export default App;

【讨论】:

【解决方案2】:

如果你这样使用它,应该可以工作:

    import React, { useState } from "react";

    export const Button = () => {
      const [getName, setName] = useState(false);
      const handleNameChange = () => {
        setName(!getName);
      };
      return (
        <button onClick={handleNameChange}>
          {getName ? "Inactive" : "active"}
        </button>
      );
    };

【讨论】:

    【解决方案3】:

    我会重命名该状态以更能描述它正在做什么:

    const [isActive, setIsActive] = useState(false);
    
    const toggle = () => {
      setIsActive(!isActive); 
    }
    
    return (
      <button onClick={toggle}>
        {isActive ? 'Active' : 'Inactive'}
      </button>
    );
    

    我认为这应该可行。

    【讨论】:

    • 我的代码是一样的,但是不知道为什么不运行并报错
    【解决方案4】:

    您需要添加渲染功能。在这种情况下返回。

    const [getName, setName] = useState(false);
    
    const handleNameChange = () => {
       setName(!getName);
    };
    
    return (
       <button onClick={handleNameChange}>
         {getName ? "Inactive" : "active"}
       </button>
    );
    

    【讨论】:

      【解决方案5】:

      您可以在按钮单击时直接使用 setter 函数。不需要做额外的功能。

      const [getName, setName] = useState(false);
      
      return (
          <button onClick={() => setName(!getName)}>
              {getName ? 'Active' : 'Inactive'}
          </button>
      );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-07-29
        • 2019-01-21
        • 1970-01-01
        • 2012-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多