首页 > 解决方案 > 单击按钮一次单击仅呈现文本

问题描述

如何创建一个按钮,而不是单击该按钮将使用反应钩子仅呈现文本

const WelcomeButton = (props) => {
  
const[welcomeBtn, setwelcomeBtn] = useState()

 const handelClick = () => {
 if() {
 retun <p>Hi John</p>
 }
}
  return (
  <div>
<button onClick={handelClick}> Welcome </button>    
  </div>
  )
  ;
};

标签: javascriptreactjsreact-hooks

解决方案


我建议使用跟踪按钮已被单击的状态,并在handleClick回调中更新/切换此值。基于此状态有条件地呈现按钮或欢迎文本。

const WelcomeButton = (props) => {
  // initial state true to show button
  const [welcomeBtn, setWelcomeBtn] = React.useState(true);

  const handelClick = () => {
    // toggle false to hide button and display welcome message
    setWelcomeBtn(false);
  };

  return (
    <div>
      {welcomeBtn ? (
        <button onClick={handelClick}> Welcome </button>
      ) : (
        <p>Hi John</p>
      )}
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(
  <WelcomeButton />,
  rootElement
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root" />


推荐阅读