reactjs - React Native 从 onPress 事件中获取元素属性
问题描述
我正在尝试在 React Native 中创建一个数字着色页。我的目标是当用户按下单个 SVG 路径时,它会改变填充颜色。
问题是 onPress 事件处理程序不能专门应用于路径,所以我不得不将它添加到 TouchOpacity。我需要从那个 onPress 事件中知道选择了哪个路径。我为每个路径都添加了名称和 id,我无法弄清楚如何从点击事件中提取这些属性。
const selectedColor = '#FF0000';
const [ color1, setColor1 ] = useState(WHITE);
const [ color2, setColor2 ] = useState(WHITE);
const [ color3, setColor3 ] = useState(WHITE);
const onPressSvg = (event) => {
const num = // <--- IDK?
switch (num) {
case 1: setColor1(selectedColor); break;
case 2: setColor2(selectedColor); break;
case 3: setColor3(selectedColor); break;
}
};
return (
<TouchableOpacity onPress={onPressSvg}>
<Svg viewBox="0 0 144 144">
<Path
id="1"
name="1"
fill={color1}
d="..."
/>
<Path
id="2"
name="2"
fill={color2}
d="..."
/>
<Path
id="3"
name="3"
fill={color3}
d="..."
/>
</Svg>
</TouchableOpacity>
);
解决方案
好的,这现在已经足够好了。我看到从 Web 和 IOS 返回的不同事件对象。这不是最漂亮的解决方案,但我现在没有被卡住。耶!
let path1 = null;
let path2 = null;
let path3 = null;
const ColoringPage = () => {
const [ color1, setColor1 ] = useState(WHITE);
const [ color2, setColor2 ] = useState(WHITE);
const [ color3, setColor3 ] = useState(WHITE);
const onPressSvg = (event) => {
if (typeof event.nativeEvent.target === 'object') {
// Web
switch (event.nativeEvent.target.id) {
case '1': setColor1(color); break;
case '2': setColor2(color); break;
case '3': setColor3(color); break;
}
} else {
// IOS
switch (event.nativeEvent.target) {
case path1.root._nativeTag: setColor1(color); break;
case path2.root._nativeTag: setColor2(color); break;
case path3.root._nativeTag: setColor3(color); break;
}
}
};
return (
<TouchNavigation onPress={onPressSvg}>
<Svg viewBox="0 0 144 144">
<Path
ref={(component) => { path1 = component}}
id={1}
fill={color1}
d="..."
/>
<Path
ref={(component) => { path2 = component}}
id={2}
fill={color2}
d="..."
/>
<Path
ref={(component) => { path3 = component}}
id={3}
fill={color3}
d="..."
/>
</Svg>
</TouchNavigation>
);
};
推荐阅读
- html - 我的 css 文件不起作用,直到我更改 css 文件的名称
- angular - Angular6:使用innerHTML时显示嵌入页面的图像时出现问题?
- xamarin - 如何获得 Xamarin 帐户?
- twitter-bootstrap - 引导程序无法从 maxcdn ERR_CONNECTION_RESET 加载
- actions-on-google - 如何使用 Google Home App 配置自定义 Google Assistant 设备?
- javascript - 如何存根一系列 HTTP 请求并测试 Web 应用程序的 UI
- c# - 在 DataGridTemplateColumn 中使用 TemplateSelector 时绑定不再起作用
- python - 在 Python 中将日期时间对象作为字符串调用
- spring - 弹簧休息控制器具有生成默认值的请求正文?
- java - 发布不支持的媒体类型