javascript - 如何在 React Native 中的按钮函数上传递函数参数?

标签 javascript react-native bind

我对 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/

相关文章:

javascript - 登录后重定向

javascript - 正则表达式匹配方括号内的字符串,以冒号分隔

javascript - Jasmine Javascript 单元测试附加 HTML

ios - React Native:iOS中的透明Stack Navigator不起作用

javascript - 绑定(bind)函数不返回对象的引用

javascript - 添加/删除类淡入淡出不起作用

ios - 在 React Native 前台设置 PushNotificationIOS 时发出警告

javascript - 使用连接到容器组件转换无状态组件 - 优化

c++ - boost 函数绑定(bind)编译时出现转换错误

javascript - 无法使用 .bind 更改分配给该对象的值