首页 > 解决方案 > 无法单击 SVG 内的项目

问题描述

我有非常奇怪的行为React-native-svg,例如我有这样的示例圆圈:

<Circle
    cx={props.x}
    cy={props.y}
    r={15}
    // stroke={selected ? 'green' : 'white'}
    stroke="green"
    // strokeWidth={}
    // fill="blue"
    fill="none"
    onPress={() => {
      console.log('pressed', props.index);
      clickable(!boolean);
      setSelected(!selected);
    }}
    // fill={selected ? 'blue' : 'grey'}
  />

我完全可以像平常一样点击它,但是,如果我想要另一个圆圈,或者只是我把 SVG 包裹在圆圈上,我不能再点击圆圈了!!!为什么 ???

  <Svg> <========== I CAN NOT DO ANYTHING
      <Circle
        cx={props.x}
        cy={props.y}
        r={15}
        // stroke={selected ? 'green' : 'white'}
        stroke="green"
        // strokeWidth={}
        // fill="blue"
        fill="none"
        onPress={() => {
          console.log('pressed', props.index);
          clickable(!boolean);
          setSelected(!selected);
        }}
        // fill={selected ? 'blue' : 'grey'}
      />
    </Svg>

即使我在 SVG 上按下,但什么也没发生,所以如果我想在 SVG 上添加按下,我该怎么做?

编辑:我通过用 G 替换 SVG 来解决

     <G>   <------- it work ?????
      <Circle
        cx={props.x}
        cy={props.y}
        r={15}
        stroke="green"
        fill="none"
        onPress={() => {
          console.log('pressed', props.index);
          clickable(!boolean);
          setSelected(!selected);
        }}
       
      />
    </G>

那么为什么它与???????

标签: reactjsreact-nativereact-native-svg

解决方案


在 svg 上设置点击事件不是一个好主意。您可以将该 svg 放在按钮中,并在按钮本身上添加 onClick 事件。

<button className="hidden-btn" onClick={() => {
          console.log('pressed', props.index);
          clickable(!boolean);
          setSelected(!selected);
        }}
>
  <Circle
     cx={props.x}
     cy={props.y}
     r={15}
     stroke="green"
     fill="none"       
  />
</button

如果需要,可以使用一些 CSS 来隐藏按钮

.hidden-btn {
  background: transparent;
  border: none !important;
}

推荐阅读