reactjs 我可以用React为SVG中的路径分配一个click事件吗?

but5z9lq  于 2023-03-01  发布在  React
关注(0)|答案(2)|浏览(254)

让我们看看我的简单代码并讨论它

import React, { useState } from "react";
import styled from "styled-components";
import { ReactComponent as SouthAmerica } from "./assets/South_America.svg";

const StyledSouthAmerica = styled(SouthAmerica)`
  path {
    fill: ${(props) =>
      props.fillColor}; // Change the color to whatever you want
    stroke: ${(props) => props.stroke};
    cursor: pointer;
  }
`;
export default function Geomap() {
  const [isGeomapSelct, setIsGeomapSelct] = useState(false);

  const handleClick = () => {
    console.log("Button clicked!");
    setIsGeomapSelct(true);
  };

  return (
    <StyledSouthAmerica
      fillColor={isGeomapSelct === true ? "#C9E9E1" : ""}
      stroke={isGeomapSelct === true ? "#61AD96" : ""}
      onClick={handleClick}
    >
      <path />
    </StyledSouthAmerica>
  );
}

我不想为SVG组件提供click事件,我想在path标记上触发onClick事件
我试过在路径标签中使用onClick,但它根本不起作用,有可能解决这个问题吗,请帮助。

mwyxok5s

mwyxok5s1#

是的,您可以使用React将click事件分配给SVG中的路径。
为此,您可以使用React SVG组件创建一个SVG元素,然后在其中创建一个path元素,然后使用onClick属性为path元素分配一个click事件处理程序。q

import "./styles.css";

export default function MyComponent() {
  const handleClick = () => {
    console.log('Path clicked!');
  };

  return (
    <svg width="100" height="100">
      <path d="M10 10 H 90 V 90 H 10 L 10 10" onClick={handleClick} />
    </svg>
  );
}
gpfsuwkq

gpfsuwkq2#

使用css pointer events属性,将paths设置为all,将路径以外的其余区域设置为none

import React, { useState } from "react";
import styled from "styled-components";
import { ReactComponent as SouthAmerica } from "./assets/South_America.svg";

const StyledSouthAmerica = styled(SouthAmerica)`
 //Here set to none
  pointer-events: none;
  & path {
    fill: ${(props) =>
      props.fillcolor}; // Change the color to whatever you want
    stroke: ${(props) => props.stroke};
   //Here allow only for paths
    pointer-events: all;
    cursor: pointer;
  }
`;

export default function Geomap() {
  const [isGeomapSelct, setIsGeomapSelct] = useState(false);

  const handleClick = () => {
    console.log("Button clicked!");
    setIsGeomapSelct(pre=>!pre);
  };

  return (
    <StyledSouthAmerica
      fillcolor={isGeomapSelct === true ? "#C9E9E1" : ""}
      stroke={isGeomapSelct === true ? "#61AD96" : ""}
      onClick={handleClick}
    ></StyledSouthAmerica>
  );
}

注意,在camelCase中传递fillColor将不会被DOM识别,而是使用fillcolor

相关问题