【问题标题】:How can I make my HTML update when I press the update button?当我按下更新按钮时,如何进行 HTML 更新?
【发布时间】:2021-06-26 22:35:26
【问题描述】:
   function setTodoInfo(id) {

      let todoInfo = todoInfoRef.current.value
      if(todoInfo === "") return
     todo.info = todoInfo
      todoInfoRef.current.value = null

    }


  <>
   <h1 className="delete-button"> hi, {todo.info} </h1>
   <form>
   <input type="text" ref={todoInfoRef}/>
   </form>
  <button onClick={closeInfo} className="delete-button" > Close </button>
   <button onClick={setTodoInfo}> Set Info</button>
   </>

当我点击设置信息按钮时,它会更新待办事项上的信息属性,但是当你点击它时它不会显示它,你必须关闭它并重新打开它才能看到更新的信息

【问题讨论】:

  • 你缺少一些可以在 React 文档中找到的基础知识。此外,您发布的代码不足以提供答案。

标签: javascript reactjs react-hooks


【解决方案1】:

react 使用引用来查看它是否应该重新渲染。使用 refs 意味着引用不会改变...

正如所指出的,您应该真正看到有关如何使其成为“反应方式”的文档

如果你真的需要使用引用,那么你可以添加一些“渲染”功能。

useState 放入一个整数或其他东西,然后调用setState 来更改它的值...这应该会强制渲染。

【讨论】:

    【解决方案2】:
     function useForceUpdate(){
         const [value, setValue] = useState(0); // integer state
         return () => setValue(value => value + 1); // update the state to force 
    
     }
    
    
    
      (inside functional component)
       const forceUpdate = useForceUpdate();
     call forceUpdate where needed
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多