javascript - 单击按钮一次单击仅呈现文本
问题描述
如何创建一个按钮,而不是单击该按钮将使用反应钩子仅呈现文本
const WelcomeButton = (props) => {
const[welcomeBtn, setwelcomeBtn] = useState()
const handelClick = () => {
if() {
retun <p>Hi John</p>
}
}
return (
<div>
<button onClick={handelClick}> Welcome </button>
</div>
)
;
};
解决方案
我建议使用跟踪按钮已被单击的状态,并在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" />
推荐阅读
- kubernetes - 使用 terraform 将公共 GKE 更改为私有 GKE 集群
- ios - Fastlane Automating 2FA with account Enterprise
- python - 如何在 National Instruments PXI-8840 控制器上运行 python 脚本
- pytorch - 使用 Pytorch 进行图像分类
- vue.js - vue中使用动态组件时如何提高性能?
- mongodb - Mongodb atlas 专用集群:如何与 AWS 建立对等连接,然后在不将 ip 列入白名单的情况下访问集群
- linux - 如何在 amazon linux 上安装新的 relic
- laravel - 使用 with() 从多个表中选择特定列并选择 ()
- apache-spark - Pyspark dataframe parquet vs delta:不同的行数
- mysql - MYSQL - 存储过程查询简化