Master React.js: Components for Modern Web
Sobre a Aula

Communication between Components

Communication between components is essential in React applications to transmit data and events between different parts of the interface. There are two main ways to achieve this communication: props and events.

Props

Props are used to pass data from a parent component to a child component. This allows information to be shared hierarchically in the component tree. For example:

// Parent Component
function App() {
  return <ChildComponent name="John" />;
}

// Child Component
function ChildComponent(props) {
  return <p>Hello, {props.name}!</p>;
}

Events

Events are used to transmit user actions or interactions from a child component to a parent component.

This is done by defining callback functions in the parent component, which are then passed as props to the child component. For example:

// Parent Component
function App() {
  function handleClick() {
    alert("Button clicked!");
  }

  return <ChildComponent onClick={handleClick} />;
}

// Child Component
function ChildComponent(props) {
  return <button onClick={props.onClick}>Click me</button>;
}

These techniques of communication between components are fundamental for creating robust and flexible React applications, allowing different parts of the interface to interact with each other efficiently and organized.

Entrar na conversa
Rolar para cima