Component - Callback props
This React Native component shows how a parent passes a function (callback) to a child. The child calls this function when a button is pressed. This lets the parent know about the child's action and update its own state.
This React Native component shows how a parent passes a function (callback) to a child. The child calls this function when a button is pressed. This lets the parent know about the child's action and update its own state.
App ├─ View (container) │ ├─ Text (display message) │ └─ ChildButton (custom component) │ └─ Button (pressable)
callback props in React Native components?onPress from a parent to a child component in React Native?onPress={handlePress}, which is valid JSX syntax.function Parent() {
const handleClick = () => console.log('Clicked!');
return <Child onPress={handleClick} />;
}
function Child({ onPress }) {
return <Button title="Press me" onPress={onPress} />;
}handleClick as onPress prop to Child.onPress prop as the button's onPress handler, so pressing calls handleClick.function Parent() {
const handlePress = () => alert('Pressed');
return <Child onPress={handlePress()} />;
}
function Child({ onPress }) {
return <Button title="Click" onPress={onPress} />;
}onPress={handlePress()}, the function is called immediately, passing its result (undefined) instead of the function.onPress={handlePress}.Pass the test and this pattern moves unknown