Zum Inhalt springen

Callbacks

Ein Callback nur mit JavaScript

function rueckruf() {
console.log("Rückruf!!!");
}
// Die Funktion rueckruf wird nach 5 Sekunden aufgerufen
setTimeout(rueckruf, 5000);

Ein Callback mit React

App.tsx:

import { Komponente } from "./Komponente"
function myCallback(name: string) {
console.log("Telefon klingelt bei ...")
console.log(name)
}
function App() {
return (
<>
<Komponente buttonText="buttonText" callback={myCallback} />
</>
)
}
export default App

Komponente.tsx:

type Props = {
buttonText: string;
callback: (name: string) => void;
}
export function Komponente(props: Props) {
function makeCallback() {
console.log("Ich rufe jetzt zurück!")
props.callback("Robin");
}
return <button onClick={makeCallback}>{props.buttonText}</button>;
}