简体   繁体   English

如何在本机反应中以编程方式单击按钮

[英]how to click a button programmatically in react native

i have tried couple of ways to figure out how to perform click event programmatically, i found that useRef can solve the problem.我尝试了几种方法来弄清楚如何以编程方式执行点击事件,我发现 useRef 可以解决问题。 but i tried it doesn't seems to work for me.但我试过它似乎对我不起作用。 below is the code,下面是代码,

//declaration
const reff=useReff(null);

//button design

<Button
onPress={()=>{console.log('Pressed')}}
title="Press me"
ref={reff}
/>

//Triggering the event
reff.current.onPress();

its giving me an error "onPress is undefined".它给了我一个错误“onPress 未定义”。 i have tried with onClick(),click(),press() nothing worked for me unfortunately.不幸的是,我尝试过 onClick()、click()、press() 对我没有任何帮助。

can someone help me on this please..有人可以帮我解决这个问题吗..

import React, { useRef } from 'react';
import { Button, View } from 'react-native';

const App = () => {
  const btnRef = useRef();

  return (
    <View>
      <Button
        title="Ref"
        onPress={() => {
          console.info('Ref props', btnRef.current.props);
          btnRef.current.props.onPress();
          btnRef.current.props.onHandlePress();
        }}
      />
      <Button
        title="Click Me"
        ref={btnRef}
        onPress={() => console.log('onPress props called')}
        onHandlePress={() => console.log('Custom onHandlePress called')}
      />
    </View>
  );
};

export default App;

I'm using react native cli我正在使用反应原生 cli

"react": "16.13.1",
"react-native": "0.63.4"

I guess, whatever props that passed in Button component can be accessed by calling ref.current.props.anyprops , Good luck!我想,在 Button 组件中传递的任何道具都可以通过调用ref.current.props.anyprops来访问,祝你好运!

Try this once, you just need to set ref:试试这个,你只需要设置 ref:

<Button id={buttonId}
  onClick={e => console.log(e.target)}
  ref={(ref) => { this.myButton = ref; }}
 
/> 

and then you can add this in your function:然后你可以在你的 function 中添加这个:

yourFunction = () => {
  this.myButton.click()
}

Hope it helps.希望能帮助到你。 feel free for doubts随时怀疑

This works for me:这对我有用:

  <Button
    onClick={() => console.log('pressed')}
    title="Press me"
    />

Just use the curly braces when you write the callback functions on multiple lines.当您在多行上编写回调函数时,只需使用大括号即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM