【问题标题】:Want to display the increment counter value on screen想要在屏幕上显示增量计数器值
【发布时间】:2023-01-25 15:15:52
【问题描述】:

在不重新渲染的情况下,组件需要在屏幕上显示增量值(changes.current)。单击按钮时,会发生增量,它会显示在控制台上但不会更改屏幕上的值。 我们需要显示增量值(changes.current)。我也试过 document.getElementById("p_id") 但它不起作用。

import "./styles.css";
import React, { useRef } from "react";

export default function App() {
  let changes = useRef(0);
  const changingValue = () => {
    changes.current++;
    //To print on console
    console.log("New Value: " + changes.current);
  };
  // Statement to check the rerendering happening or not
  console.log("rendering not happening");

  return (
    <div className="App">
      {/* Button for click */}
      <button onClick={changingValue}>
        <b>Click me</b>
      </button>
      <p id='p_id'>{changes.current}</p>
    </div>
  );
}

期待: 单击按钮时应显示更新的值: enter image description here`

【问题讨论】:

    标签: javascript reactjs typescript react-hooks ref


    【解决方案1】:

    改变 React ref 不会触发组件重新渲染。更新状态将触发重新渲染。

    例子:

    import React, { useEffect, useState } from "react";
    
    export default function App() {
      const [changes, setChanges] = useState(0);
    
      const changingValue = () => {
        // Enqueue state update to increment the current
        // state value by 1, trigger rerender
        setChanges(c => c + 1);
      };
    
      useEffect(() => {
        console.log(changes);
      }, [changes]);
    
      return (
        <div className="App">
          <button type="button" onClick={changingValue}>
            <b>Click me</b>
          </button>
          <p>{changes}</p>
        </div>
      );
    }
    

    您可以继续在 React ref 中存储您喜欢的任何值,但为了查看任何更新的值,组件一定需要重新渲染,以便更新的 UI 可以刷新到 DOM。

    【讨论】:

      猜你喜欢
      • 2011-12-07
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 2019-11-11
      • 2023-03-16
      • 1970-01-01
      • 2014-08-01
      • 1970-01-01
      相关资源
      最近更新 更多