html - 在 React.js 的函数中尝试钩子和状态
问题描述
这段代码在语法上是否正确?我想要达到的效果是在单击按钮后出现文本......
import React, { useState } from 'react';
import './App.css';
function Example(){
const [state, setState] = useState({shows: false});
return(
<div>{state.shows && <p>hi</p>}
<button onClick={() => setState({shows: true})}>
Click me
</button>
</div>
)
}
export default Example;
解决方案
是的,但你不需要使用对象
function Example(){
const [state, setState] = useState(false);
return(
<div>{state && <p>hi</p>}
<button onClick={() => setState(true)}>
Click me
</button>
</div>
)
}
推荐阅读
- javascript - 如何通过使用 laravel 解析将使用 api 获取的 json 文件转换为 javascript 对象?
- node.js - Messagebird SMS 身份验证/OTP 用于具有节点 js 和颤振的移动应用程序
- json - oracle解析对象数组
- mysql - Cat unix 命令多线程安全吗?在多台主机上寻找并行 mysql 还原
- typescript - 如何解决我在安装 vscode 以测试我的扩展程序时遇到的错误?
- c - 使用 malloc 在 C 中存储坐标
- json - 在 Flutter 中显示来自 API 响应的完整 json 数据
- confluent-kafka-python - 融合 kakfa 生产者 KafkaError{code=_MSG_TIMED_OUT,val=-192,str="Local: Message timed out"}
- javascript - 检查所有段落中的某些单词并添加到列表中
- javascript - 如何在 Google Earth Engine 中沿 1 轴连接从图像集合中获得的数组