我对 react 还很陌生,并且无法弄清楚如何将参数传递给事件处理程序。我尝试过绑定(bind)它,但语法不正确。我指的是按钮中调用减量函数的 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
,因为您使用的是函数组件而不是类组件。
关于javascript - 如何在 React Native 中的按钮函数上传递函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61365731/