首页 > 解决方案 > 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>
);

标签: reactjsreact-nativesvgreact-native-svg

解决方案


好的,这现在已经足够好了。我看到从 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>
    );
};

推荐阅读