Programmatically Clicking Button in React Native

How to click programmatically a child component? react

You need useRef and you have to forward this ref to the Item component.

import React, { forwardRef, useRef } from 'react';

const Item = forwardRef((props, ref) => {
return <li {...props}
onClick={() => alert('clicked on Item')}
ref={ref} >MyItem</li>
})

const App = (props) => {
const itemRef = useRef(null);

return (
<div>
<button onClick={() => itemRef.current.click()}>
click item
</button>


<Item ref={itemRef} />
</div>
);
};

export default App;

React-native, render a button click dynamically

It's really inadvisable but something like this should work:

simulatePress() {
this.touchable.props.onPress();
}

render() {
return (
<TouchableOpacity ref={component => this.touchable = component} onPress={() => console.log('onPress')}>
<Text>Tap me</Text>
</TouchableOpacity
);
}

Really though, what you are trying to achieve? There is likely a better way to do it.



Related Topics



Leave a reply



Submit