首页 > 解决方案 > React onClick 在第一次点击时不触发,第二次点击很好

问题描述

我正在使用两个组件,例如FirstComponentSecondComponent。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>
  );
}



标签: javascriptreactjs

解决方案


来自 React 官方文档:-

密钥应该是稳定的、可预测的和唯一的。不稳定的键(如 Math.random() 产生的键)会导致许多组件实例和 DOM 节点被不必要地重新创建,这可能会导致性能下降和子组件中的状态丢失。

您已经使用Math.random()了钥匙,我认为这就是您可能会遇到奇怪行为的原因。删除它并使用更可靠的,如唯一 id


推荐阅读