javascript - React onClick 在第一次点击时不触发,第二次点击很好
问题描述
我正在使用两个组件,例如FirstComponent和SecondComponent。SecondComponent 在 FirstComponent 上呈现。我将hanldeClick()函数从 FirstComponent 发送到 SecondComponent。但是 hanldeClick() 函数在第一次点击时没有响应。
我的代码:
//First Component
export function FirstComponent(props) {
const handleClick = () => {
console.log('please response');
};
return (
<div>
<SecondComponent handleClick ={handleClick } />
</div>
);
}
//Second Component
export function SecondComponent(props) {
const { handleClick } = props;
return (
<div>
<Table>
<TableBody>
{mayArray.map(file => (
<TableRow key={Math.random()}>
......................
<TableCell>
<Button
onClick={() => {
hanldeClick();
}}>
Cros
</Button>
</TableCell>
..........................
</TableRow>
))}
</TableBody>
</Table>
</div>
);
}
解决方案
来自 React 官方文档:-
密钥应该是稳定的、可预测的和唯一的。不稳定的键(如 Math.random() 产生的键)会导致许多组件实例和 DOM 节点被不必要地重新创建,这可能会导致性能下降和子组件中的状态丢失。
您已经使用Math.random()
了钥匙,我认为这就是您可能会遇到奇怪行为的原因。删除它并使用更可靠的,如唯一 id。
推荐阅读
- terraform - CodeDeploy 命令与 terraform 状态混淆
- python - 在数据流入 GCP 时迭代存储桶内容
- reactjs - 我如何只希望单击的项目出现在模式上?
- python - Python 对 CSV 的请求
- java - Spring Boot 可运行 jar 中的 ANT 类路径
- vue.js - VueJS - 如何在同一个组件中使用道具来指定另一个组件中的值
- html - 如何删除输入类型文件的默认占位符并获取占位符,如下所示?
- angular - 无法连接到 test.mosquitto.org 进行测试
- c# - C#字符串中的引号和斜线标记
- raspberry-pi - 在树莓派上开始使用 reportlab