Basic overview of how callback functions work in React.js:
function myCallback() {
// Code to be executed when the callback is called
}
// ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
// Define the callback function
function myCallback() {
console.log('Callback function called');
}
return (
<div>
<h1>Parent Component</h1>
<ChildComponent callback={myCallback} />
</div>
);
}
export default ParentComponent;
领英推荐
// ChildComponent.js
import React from 'react';
function ChildComponent(props) {
function handleClick() {
// Call the callback function when the button is clicked
props.callback();
}
return (
<div>
<h2>Child Component</h2>
<button onClick={handleClick}>Click me</button>
</div>
);
}
export default ChildComponent;
This is a basic example of using callback functions in React.js. Callbacks are also commonly used with asynchronous operations like fetching data from an API, where you pass a callback function to handle the data once it's available.
Remember that in modern React, you can also use hooks like useState and useEffect to manage state and side effects, which can sometimes replace the need for callback functions in certain scenarios.