【问题标题】:React change only clicked button text [Looped]反应更改仅单击的按钮文本[循环]
【发布时间】:2022-02-09 18:01:25
【问题描述】:

当我单击按钮时,运行一个名为 AddWait 的函数,但它会向所有按钮添加等待文本。我尝试使用useRef,但事情变得一团糟。 图片;

我用 jquery 做了类似的事情;

for (let index = 0; index <= 10; index++) {
  $("#app").append(`<span>Hello ${index} </span>
  ===&gt;<button class=click-me>button ${index} </button>
  <br /><br />`);
}

$(".click-me").on("click", function (event) {
  var $this = $(this);
  console.log($this.text());

  $this.text($this.text() + "hi");
  //(... rest of your JS code)
});
 <div id="app"></div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

可以查看react app;

那么我怎样才能改变只点击按钮的文字呢?

【问题讨论】:

  • 您在每个按钮中都使用相同的 waitText 变量,因此,如果 waitText 值发生更改,那么它会反映在每个按钮中。
  • 难怪onClick 你更改了与所有按钮共享的文本。当组件重新渲染时,所有按钮的文本都会更改。您需要调整代码以使用例如带有文本的数据结构并仅更改该按钮的文本。
  • 您可以将跨度和按钮包装在 div 中,并将key 属性赋予 div 元素。

标签: javascript html reactjs


【解决方案1】:

你应该做的是将带有按钮的 div 保存到一个单独的组件中,然后 react 将更改该特定组件的按钮文本:

import { useState } from "react";
import "./styles.css";

const CustomBtn = props => {
  const { item, index } = props;
  console.log(item)
  const [waitText, setWaitText] = useState('');
  const waitThreeSeconds = () => {
    setWaitText("wait");
    setTimeout(() => setWaitText(''), 3000)
  };


  return (
    <div>
      <span>Hello {index} </span>
      <button onClick={waitThreeSeconds}>
        button {index} {waitText}
      </button>
      <br />
      <br />
    </div>
  )
}

export default function App() {
  
  return (
    <div className="App">
      {[...Array(10)].map((item, index) => (
        <CustomBtn item={item} key={index} index={index} />
      ))}
    </div>
  );
}

【讨论】:

  • 它对我有用,非常棒,非常感谢
【解决方案2】:
import { useState } from "react";
import "./styles.css";

export default function App() {
  const [waitText, setWaitText] = useState();
  const [arr,setArr] = useState([
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
  ]);
  const WaitThreeSeconds = (index) => {
    console.log("hi");
    let temp = [...arr];
    temp[index].waitText = "wait"
    setArr([...temp])
    // setWaitText("wait");
  };
  return (
    <div className="App">
      {arr.map((x, i) => (
        <div key={i}>
          <span>Hello {i} </span>
          <button onClick={()=>WaitThreeSeconds(i)}>
            button {i} {x.waitText}
          </button>
          <br />
          <br />
        </div>
      ))}
    </div>
  );
}

您可以查看沙箱代码here。 希望对您有所帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    相关资源
    最近更新 更多