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
Prevent Form Redirect or Refresh on Submit
Regular Expression to Accept Both Positive and Negative Numbers
How to Instantiate a File Object in JavaScript
Change HTML Code Without Refreshing the Page
How to Change Background Opacity When Bootstrap Modal Is Open
Use Lodash to Find Objects in an Array Matches an Id (Complex, Drilldown)
Want to Show/Hide Div Based on Dropdown Box Selection
How to Disable Eslint Rule Max Line Length for Paragraph in <Template> of Vue.Js
Npm Warn Enoent Enoent: No Such File or Directory, Open 'C:\Users\Nuwanst\Package.Json'
How to Select Every 2Nd Element of an Array in a for Loop
How to Count Unique Value from Object of Array in JavaScript
Launch Chrome Browser from Internet Explorer
React-Native React-Navigation Undefined Is Not an Object (Evaluating 'S.Value.Startswith')
How to Change Background Opacity When Bootstrap Modal Is Open
Slick Carousel - Force Slides to Have the Same Height