如何在 React Native 中的按钮函数上传递函数参数?
How to pass function arguments on button function in React Native?
我对反应还很陌生,我很难弄清楚如何将参数传递给事件处理程序。我试过绑定它,但语法不正确。我指的是调用递减函数的按钮中的 onPress。我已经在没有传递参数的情况下测试了它,只是在函数中直接调用 USER_ID 并且 onPress 具有以下语法:
onPress={decrement}
..
export default function App() {
const db = firebase.firestore().collection("users");
const [count, setCount] = useState();
const USER_ID = "INxK5dbadj6OmSn9mp6l";
const decrement = (UID) => {
var next = count - 1;
if (next >= 0) {
db.doc(UID).update({ Count: next });
db.doc(UID)
.get()
.then(function (doc) {
setCount(doc.data().Count);
});
}
};
return (
<View style={styles.container}>
<View style={styles.userContainer}>
<Text>USER 1: {count}</Text>
<View style={styles.buttonContainer}>
<Button
title="-"
onPress={() => this.decrement.bind(this, USER_ID)}
/>
</View>
</View>
</View>
);
}
感谢您的指导或帮助!
您应该使用 onClick
而不是 onPress
<button
title="-"
onClick={()=>decrement(USER_ID)}
/>
没有理由使用 bind
并且您不能使用 this
因为您使用的是函数组件而不是 class 组件。
我对反应还很陌生,我很难弄清楚如何将参数传递给事件处理程序。我试过绑定它,但语法不正确。我指的是调用递减函数的按钮中的 onPress。我已经在没有传递参数的情况下测试了它,只是在函数中直接调用 USER_ID 并且 onPress 具有以下语法:
onPress={decrement}
..
export default function App() {
const db = firebase.firestore().collection("users");
const [count, setCount] = useState();
const USER_ID = "INxK5dbadj6OmSn9mp6l";
const decrement = (UID) => {
var next = count - 1;
if (next >= 0) {
db.doc(UID).update({ Count: next });
db.doc(UID)
.get()
.then(function (doc) {
setCount(doc.data().Count);
});
}
};
return (
<View style={styles.container}>
<View style={styles.userContainer}>
<Text>USER 1: {count}</Text>
<View style={styles.buttonContainer}>
<Button
title="-"
onPress={() => this.decrement.bind(this, USER_ID)}
/>
</View>
</View>
</View>
);
}
感谢您的指导或帮助!
您应该使用 onClick
而不是 onPress
<button
title="-"
onClick={()=>decrement(USER_ID)}
/>
没有理由使用 bind
并且您不能使用 this
因为您使用的是函数组件而不是 class 组件。