【问题标题】:how to click a button programmatically in react native如何在本机反应中以编程方式单击按钮
【发布时间】:2020-06-30 13:25:57
【问题描述】:

我尝试了几种方法来弄清楚如何以编程方式执行点击事件,我发现 useRef 可以解决问题。但我试过它似乎对我不起作用。下面是代码,

//declaration
const reff=useReff(null);

//button design

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

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

它给了我一个错误“onPress 未定义”。不幸的是,我尝试过 onClick(),click(),press() 对我没有任何帮助。

有人可以帮我解决这个问题吗..

【问题讨论】:

    标签: reactjs react-native react-hooks react-native-android react-ref


    【解决方案1】:
    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;
    

    我正在使用 react native cli

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

    我猜,任何传入 Button 组件的 props 都可以通过调用 ref.current.props.anyprops 来访问,祝你好运!

    【讨论】:

      【解决方案2】:

      试试这个,你只需要设置 ref :

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

      然后你可以在你的函数中添加这个:

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

      希望对您有所帮助。如有疑问,请随意

      【讨论】:

      • 我的疑问是,onClick 事件是否适用于原生反应?如果是这样,那么 this.myButton 是什么,它是一个参考吗?
      【解决方案3】:

      这对我有用:

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

      在多行编写回调函数时,只需使用大括号即可。

      【讨论】:

      • 抱歉没有帮到我:(
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      • 2013-10-09
      • 1970-01-01
      • 2015-02-20
      • 2010-10-18
      相关资源
      最近更新 更多