以编程方式在React Native中点击按钮

3
我有一个带有testID字段的按钮。
<Button testID='someButton' onPress={someButtonClick}/>

有没有办法通过编程的方式点击一个给定testID的按钮?

你能为你定义的按钮添加一些代码吗? - Pritish Vaidya
可能是React-native,动态渲染按钮点击的重复问题。 - Revansiddh
5个回答

2
这是一个完整的实现,其中一个按钮按下另一个按钮。
import React from "react"
import { View, Button  } from 'react-native';

const someButtonClick = () => {
    console.log("button was pressed");
}

export class PressButton extends React.Component {
    constructor(props) {
        super(props);
        this.state = {}
    }
    clickButton() {
        this.button.props.onPress();
    }
    render() {
        return (
            <View>
                <Button title="another button" 
                    onPress={() => { this.clickButton()}}
                />
                <Button title="some button" testID='someButton' 
                onPress={() => { someButtonClick() }}
                    ref={(button) => {this.button = button; }}
                />          
            </View>
        )
    }
}

请注意以下事项:
  • 您需要一个ref来访问按钮。
  • 在React Native中,正确的方法是onPress(),而不是click()。
  • 事件处理程序在props中。

1
你需要创建一个引用。
<Button id={buttonId}
  onClick={e => console.log(e.target)}
  ref={(button) => { this.myButton = button; }}
  // Or something like this:
  ref={component => this.myButton = component}
/>

然后您可以在代码的其他地方访问该引用:
myFunction = () => {
  this.myButton.click()
}

如果我有多个具有不同“testID”的按钮,我该如何使用此代码来单击具有给定“testID”的按钮? - Barinder Grewal
你可以在不同的按钮上设置不同的引用,例如 ref={component => this.myButton1 = component}ref={component => this.myButton2 = component} - A. Larsson

1
const uploadbtn = useRef();

我正在隐藏这个按钮以便通过编程来按它。
 <Button
    ref={uploadbtn}
    buttonStyle={{ width: 0, height: 0, opacity: 0, display: "none" }}
    onPress={pickImage}
  />

然后使用类似于这样的函数来按下按钮。
  const test = () => {
    uploadbtn.current.handleOnPress();
  };

-1

在渲染代码中尝试这个。

<div className="container" hidden >
   <button onClick={this.submit} ref={(button) => { this.btn = button }} />
</div>

在函数中

btn = () => {
   this.btn.click()
}

在 else 代码中

this.btn()

问题是"React Native"。 - Luke Brandon Farrell

-3

在 render() 函数中

 <button type='button' onClick="{this.btnClickFunc.bind(this)}">buton</button>

 function btnClickFunc(e){
    var value = e.target.value;

    }

希望对你有所帮助


这完全不是他所要求的。 - A. Larsson
我在问不同的问题。 - Barinder Grewal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接