Was sind React “Props”?
In React können wir mithilfe von Props (vergleichbar mit HTML-Attributen) Daten bzw. Funktionen an Komponenten übergeben.
Beispiele “Attributes”
Angenommen wir haben das folgende Objekt:
export const CORE_CONCEPTS = [
{
image: componentsImg,
title: 'Components',
description:
'The core UI building block - compose the user interface by combining multiple components.',
},
{
image: jsxImg,
title: 'JSX',
description:
'Return (potentially dynamic) HTML(ish) code to define the actual markup that will be rendered.',
},
{
image: propsImg,
title: 'Props',
description:
'Make components configurable (and therefore reusable) by passing input data to them.',
},
{
image: stateImg,
title: 'State',
description:
'React-managed data which, when changed, causes the component to re-render & the UI to update.',
},
];
Es gibt verschiedene Wege Props zu übergeben. Wir können das Objekt einzeln übergeben und per “destructuring” nutzen:
<CoreConcept
title={CORE_CONCEPTS[0].title}
description={CORE_CONCEPTS[0].description}
image={CORE_CONCEPTS[0].image} />
export default function CoreConcept({ concept }) {
// Use concept.title, concept.description etc.
// Or destructure the concept object: const { title, description, image } = concept;
}
Oder wir übergeben das Objekt komplett:
<CoreConcept
{...CORE_CONCEPTS[0]} />
export default function CoreConcept({ ...concept }) {
//..concept groups multiple values into a single object
// Use concept.title, concept.description etc.
//Or destructure the concept object: const { title, description, image} = concept;
}
“Children Props”
Es gibt auch die Möglichkeit Daten über das children prop zu setzen. Das folgende Beispiel zeigt den Unterschied:
//Children Variante
<TabButton>Components</Tabbutton>
function TabButton({children}){
return <button>{children}</button>;
}