javascript 在Reactjs中启用按钮后,没有调用onClick函数

oiopk7p5  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(153)

我有一个textarea和一个button,默认情况下按钮是禁用的,当用户开始输入时,我启用按钮被单击,但问题是,onClick函数没有被调用,而disabled = false已经被设置。
我看过这个:button onClick doesn't work when disabled=True is initialized (Reactjs)看起来是个好主意,但是在我使用新值setState之后,我的组件正在重新呈现,我真的不希望这样。

const refText = useRef(null);
const refBtn = useRef(null);

function handleBtnStatus(e) {
    let text = e.target.value;
    if(text.replace(/\s/g, "").length > 0) {
        refBtn.current.disabled = false;
    }
    else {
        refBtn.current.disabled = true;
    }
}

function postThis() {
    console.log("You posted! Text:", refText.current.value);

    // disable again
    refBtn.current.disabled = true;

    // delete previous text wrote
    refText.current.value = "";
}

return (
    <>
        {isLogged && (
            <div className="container">
                <div className="content">
                    <div className="utool-item-text">
                        <textarea name="textArea" placeholder="Write something.." ref={refText} onChange={(e) => handleBtnStatus(e)}></textarea>
                    </div>
                    <div className="utool-item-post">
                        <button className="ust-btn-post" ref={refBtn} disabled={true} onClick={postThis}>Da Tweet</button>
                    </div>
                </div>
                <div className="posts-section">
                    <div className="list-posts">
                        {posts.map((p) => {
                            return (p.hidden === false ? (
                                <div className="post" key={p.id}>
                                    <div className="post-text">
                                        <span>{p.text}</span>
                                    </div>
                                </div>
                            ) : (''))
                        })}
                    </div>
                </div>
            </div>
        )}
    </>
)

有人帮忙吗?

y53ybaqx

y53ybaqx1#

使用状态而不是引用,重新呈现适合您的情况
简化示例:

import React, { useState } from 'react';

const SimpleExample = () => {
  const [textAreaValue, setTextAreaValue] = useState('');

  return (
    <>
      <button disabled={!textAreaValue} onClick={() => console.log('onClick handler')}>
        click me
      </button>
      <textarea value={textAreaValue} onChange={(e) => setTextAreaValue(e.target.value)} />
    </>
  );
};

我建议检查Use state or refs in React.js form components?

相关问题