【问题标题】:How do I create image maps (clickable areas on an image using <map >) with React and JSX?如何使用 React 和 JSX 创建图像映射(使用 <map > 在图像上的可点击区域)?
【发布时间】:2021-02-19 19:45:28
【问题描述】:

我正在尝试使用钩子在 React 中创建一个功能组件,该钩子将呈现具有可点击区域的图像。我看过其他建议使用 react-image-mapper 或 react-img-mapper(持续支持)的帖子,但我想了解如何在 JSX 上下文中正确使用 useMap 属性来解决这个问题。

下面的代码可以编译,但是当我点击可点击区域时没有任何反应。我想我需要替换 img 标签中的 useMap 属性以将其正确链接到 map 标签,但我一直坚持如何做到这一点。代码如下:

    import React, {useState} from 'react';

    export const VanillaMapper = (props) => {
       const [height, setHeight] = useState(500);
       const [width, setWidth] = useState(1000);
       const [url, setUrl] = useState("https://c1.staticflickr.com/5/4052/4503898393_303cfbc9fd_b.jpg");
       const [alt, setAlt] = useState("generic");

       const handleOnClick = () => {
        console.log("You have clicked in the specified area")
    }

    return (
        <div>
            <img src={url} height={height} width={width} alt={alt} useMap="#workmap"/>
            <map name="workmap">
                <area shape="poly" coords="50,47,56,454,257,357,254,139" alt="test" onClick={()=>handleOnClick}/>
            </map>
        </div>
    )
}

【问题讨论】:

    标签: javascript html reactjs jsx


    【解决方案1】:

    下面是代码运行的原因:

    1. 我需要在区域标签中添加一个 href 属性
    2. 我需要防止在单击可点击区域时重定向到 href 的默认行为。为此,我需要按如下方式更改我的代码:
        const handleOnClick = (e) => {
            e.preventDefault();
            console.log("You have clicked in the specified area")
        }
    
            return (
            <div>
                <img src={url} height={height} width={width} alt={alt} useMap="#workmap"/>
                <map id = "workmap" name="workmap">
                    <area shape="poly" coords="50,47,56,454,257,357,254,139" alt="test" href="https://c1.staticflickr.com/5/4052/4503898393_303cfbc9fd_b.jpg" onClick={handleOnClick}/>
                </map>
            </div>
        )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-12
      • 1970-01-01
      相关资源
      最近更新 更多