简体   繁体   English

反应 onClick 未在组件上触发

[英]React onClick not firing on component

I'm using Remix with React and TS.我正在将 Remix 与 React 和 TS 一起使用。 I have a simple class component called Map.tsx, that is used in index.tsx.我有一个简单的 class 组件,名为 Map.tsx,用于 index.tsx。

Map.tsx Map.tsx

class Map extends React.Component {
  constructor(props: any) {
    super(props);
    this.regionClicked = this.regionClicked.bind(this);
  }

  render() {
    return (
      <div>
        <button onClick={() => alert("ciao")}>a</button>
      </div>
    )
  }
}

index.tsx索引.tsx

import Map from "../components/index/map/Map";

class Index extends React.Component {
  constructor(props: any) {
    super(props);
  }

  render() {
    return (
      <div>
        <Map />
      </div>
    )
  }
}

I'm not sure what is your problem.我不确定你的问题是什么。 But in the file Map.tsx you need declare the method regionClicked or remove this line但是在文件Map.tsx中,您需要声明方法regionClicked或删除此行

class Map extends React.Component {
  constructor(props: any) {
    super(props);
    this.regionClicked = this.regionClicked.bind(this);
  }
  regionClicked() {
    alert("ciao");
  }
  render() {
    return (
      <div>
        <button onClick={this.regionClicked}>a</button>
      </div>
    );
  }
}

Fixed by using the tag in the root.tsx file.通过使用 root.tsx 文件中的标记进行修复。 Example available here此处提供示例

import { Scripts } from "remix";

function Document({ children }: { children: React.ReactNode; title?: string }) {
  return (
    <html lang="en">
      <head>
        <Meta />
        <Links />
      </head>
      <body>
        <Header />
        {children}
        <Footer />
        <Scripts />
        {process.env.NODE_ENV === "development" ? <LiveReload /> : null}
      </body>
    </html>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM