简体   繁体   English

为什么 React 按钮在点击时不调用 function

[英]why is React button not calling function on click

when I changed the disabled of button from true to false, it messed my onClick, why is that, and how to solve it?当我将button的禁用从 true 更改为 false 时,它弄乱了我的 onClick,这是为什么,以及如何解决?

 const Component = () => { const refrence = React.useRef(null) setTimeout(() => { refrence.current.disabled = false }, 1000); const handleClick = () => console.log('clicked') return ( <div> <button onClick={handleClick} ref={refrence} disabled>click me</button> </div> ) } ReactDOM.render( <Component />, document.getElementById("root") );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script><div id="root"></div>

Issue问题

The issue here is that the React ref is mutating the DOM, but React isn't made aware of this and so Component isn't rerendered with a working button allowing the onClick event to go through.这里的问题是 React ref 正在改变 DOM,但 React 并没有意识到这一点,因此不会使用允许onClick事件通过 go 的工作按钮重新渲染Component This is the main reason why direct DOM manipulations are considered anti-pattern in React.这就是为什么直接 DOM 操作在 React 中被认为是反模式的主要原因。

Additionally, you are setting a timeout to occur every render, though this would have minimal effect it's still unnecessary and would be considered an unintentional side-effect.此外,您正在设置每次渲染时发生的超时,尽管这会产生最小的影响,但它仍然是不必要的,并且会被认为是无意的副作用。

Solution解决方案

Use component state and update state in a mounting useEffect hook to trigger a rerender.在安装useEffect挂钩中使用组件 state 并更新 state 以触发重新渲染。

const Component = () => {
  const [isDisabled, setIsDisabled] = useState(true);

  useEffect(() => {
    setTimeout(() => {
      setIsDisabled(false);
    }, 1000);
  }, []);
  
  const handleClick = () => console.log('clicked');
  
  return (
    <div>
      <button onClick={handleClick} disabled={isDisabled}>click me</button>
    </div>
  )
}

 const Component = () => { const [isDisabled, setIsDisabled] = React.useState(true); React.useEffect(() => { setTimeout(() => { setIsDisabled(false); }, 1000); }, []); const handleClick = () => console.log('clicked'); return ( <div> <button onClick={handleClick} disabled={isDisabled}>click me</button> </div> ) }; ReactDOM.render( <Component />, document.getElementById("root") );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script> <div id="root"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM