如何在React Native中知道单击了哪个按钮?

polhcujo  于 2022-12-14  发布在  React
关注(0)|答案(2)|浏览(96)

首先,我来自网络世界(ReactJS),所以对React Native不熟悉。

如何知道单击了哪个按钮?

示例:

const [titleOne, setTitleOne] = useState('A button 1');
const [titleTwo, setTitleTwo] = useState('A button 2');

const handlePress=(event)=>{
    /*
        if first button clicked,
        I want to write: setTitleOne(Button 1 clicked);
        
        if second button clicked,
        I want to write: setTitleTwo(Button 2 clicked);
    */
}

<View>
  <Button title={titleOne} onPress={handlePress} />
  <Button title={titleTwo} onPress={handlePress} />
</View>

提前感谢

nxagd54h

nxagd54h1#

const App = () => {

    const [titleOne, setTitleOne] = useState('A button 1');
    const [titleTwo, setTitleTwo] = useState('A button 2');

    const handlePress = (event) => {
        if (event == 1) {
            setTitleOne("Button 1 clicked")
        } else {
            setTitleTwo("Button 2 clicked")
        }
    }

    return (
        <View>
            <Button title={"titleOne"} onPress={() => handlePress(1)} />
            <Button title={"titleTwo"} onPress={() => handlePress(2)} />
        </View>

    )
}
2wnc66cl

2wnc66cl2#

通过传递一个额外的参数,例如name ...

const [titleOne, setTitleOne] = useState('A button 1');
const [titleTwo, setTitleTwo] = useState('A button 2');

const handlePress=(event, btnName)=>{
    if(btnName === "one"){
       setTitleOne("Button 1 clicked");
    }
    if(btnName === "two"){
       setTitleTwo("Button 2 clicked");
    }
}

<View>
  <Button title={titleOne} onPress={(e)=>handlePress(e,"one")} />
  <Button title={titleTwo} onPress={(e)=>handlePress(e,"two")} />
</View>

相关问题