Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Aplicación Práctica de Estilos en Línea | Técnicas de Estilizado en Aplicaciones React
Dominio de React

bookAplicación Práctica de Estilos en Línea

Creación de un componente versátil Notification que muestra texto y cambia dinámicamente la propiedad background-color según la prop behavior. El desarrollo se realizará paso a paso.

Paso 1

Se inicia creando el componente padre, App, junto con el componente hijo, Notification, utilizando la estructura básica de React.

// Import necessary dependencies and create a root element
import { createRoot } from "react-dom/client";

const root = createRoot(document.getElementById("root"));

// Child component - `Notification`
const Notification = (props) => <></>;

// Parent component - `App`
const App = () => <></>;

// Render the `App` component to the root element
root.render(<App />);

Paso 2

Para proporcionar un estilo predeterminado al componente Notification, se crea un objeto llamado notificationStyles y se asignan las siguientes propiedades: padding con el valor de "20px"; fontSize con el valor de "24px"; color con el valor de "aquamarine";

// Define default styles as an object
const notificationStyles = {
  padding: "20px",
  fontSize: "24px",
  color: "aquamarine",
};

Asignar el objeto notificationStyles como valor al atributo style del componente Notification component, el cual se aplica al elemento p retornado.

// Child component - Notification
const Notification = (props) => (
  <>
    {/* Step 2: Apply default styles using inline styles */}
    <p style={notificationStyles}></p>
  </>
);

Paso 3

En el componente App, se puede utilizar el componente Notification pasando las propiedades behavior y text. La propiedad behavior determina la apariencia de la notificación, mientras que la propiedad text especifica el texto que se mostrará dentro de la notificación.

// Parent component - `App`
const App = () => (
  <>
    {/* Step 3: Use the Notification component with behavior and text props */}
    <Notification text="Success" behavior="positive" />
    <Notification text="Failure" behavior="negative" />
    <Notification text="Information" behavior="neutral" />
  </>
);

Paso 4

Se puede implementar la lógica para colorear el fondo de cada mensaje de notificación según la propiedad behavior de la siguiente manera:

  • Si el valor de behavior es "positive", el color de fondo debe ser green;
  • Si el valor de behavior es "negative", el color de fondo debe ser red;
  • Si el valor de behavior es "neutral", el color de fondo debe ser blue.

Se puede crear una función para manejar la lógica utilizando la sentencia switch de JavaScript. A continuación se muestra un ejemplo de cómo se puede implementar:

// Function to set background color based on `behavior` prop
const setBackgroundColor = (behavior) => {
  switch (behavior) {
    case "positive":
      return "green";
    case "negative":
      return "red";
    case "neutral":
      return "blue";
    default:
      return "transparent";
  }
};

Esta función toma la propiedad behavior como argumento y retorna el color de fondo correspondiente según el valor usando la sentencia switch. La propiedad behavior retornará un color de fondo transparent si no coincide con los casos especificados.

Incorporar esta función en el objeto de estilos del componente:

// Child component - `Notification`
const Notification = (props) => (
  <>
    {/* Step 2, : Apply default styles using inline styles */}
    {/* Step 4, : Apply the value for the `background-color` property 
    based on the `behavior` prop */}
    <p
      style={{
        ...notificationStyles,
        backgroundColor: setBackgroundColor(props.behavior),
      }}
    >
      {props.text}
    </p>
  </>
);

Se utilizan convenciones de JavaScript para asegurar la estructura adecuada del objeto de estilos. Primero, se expande el objeto existente notificationStyles. Luego, se introduce una propiedad adicional, backgroundColor, cuyo valor se deriva de la cadena retornada por la función setBackgroundColor.

Código completo de la aplicación:

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 3

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Suggested prompts:

Can you show me the complete code for the Notification component?

How can I customize the colors for different behaviors?

Can you explain how the style merging works in the Notification component?

Awesome!

Completion rate improved to 2.17

bookAplicación Práctica de Estilos en Línea

Desliza para mostrar el menú

Creación de un componente versátil Notification que muestra texto y cambia dinámicamente la propiedad background-color según la prop behavior. El desarrollo se realizará paso a paso.

Paso 1

Se inicia creando el componente padre, App, junto con el componente hijo, Notification, utilizando la estructura básica de React.

// Import necessary dependencies and create a root element
import { createRoot } from "react-dom/client";

const root = createRoot(document.getElementById("root"));

// Child component - `Notification`
const Notification = (props) => <></>;

// Parent component - `App`
const App = () => <></>;

// Render the `App` component to the root element
root.render(<App />);

Paso 2

Para proporcionar un estilo predeterminado al componente Notification, se crea un objeto llamado notificationStyles y se asignan las siguientes propiedades: padding con el valor de "20px"; fontSize con el valor de "24px"; color con el valor de "aquamarine";

// Define default styles as an object
const notificationStyles = {
  padding: "20px",
  fontSize: "24px",
  color: "aquamarine",
};

Asignar el objeto notificationStyles como valor al atributo style del componente Notification component, el cual se aplica al elemento p retornado.

// Child component - Notification
const Notification = (props) => (
  <>
    {/* Step 2: Apply default styles using inline styles */}
    <p style={notificationStyles}></p>
  </>
);

Paso 3

En el componente App, se puede utilizar el componente Notification pasando las propiedades behavior y text. La propiedad behavior determina la apariencia de la notificación, mientras que la propiedad text especifica el texto que se mostrará dentro de la notificación.

// Parent component - `App`
const App = () => (
  <>
    {/* Step 3: Use the Notification component with behavior and text props */}
    <Notification text="Success" behavior="positive" />
    <Notification text="Failure" behavior="negative" />
    <Notification text="Information" behavior="neutral" />
  </>
);

Paso 4

Se puede implementar la lógica para colorear el fondo de cada mensaje de notificación según la propiedad behavior de la siguiente manera:

  • Si el valor de behavior es "positive", el color de fondo debe ser green;
  • Si el valor de behavior es "negative", el color de fondo debe ser red;
  • Si el valor de behavior es "neutral", el color de fondo debe ser blue.

Se puede crear una función para manejar la lógica utilizando la sentencia switch de JavaScript. A continuación se muestra un ejemplo de cómo se puede implementar:

// Function to set background color based on `behavior` prop
const setBackgroundColor = (behavior) => {
  switch (behavior) {
    case "positive":
      return "green";
    case "negative":
      return "red";
    case "neutral":
      return "blue";
    default:
      return "transparent";
  }
};

Esta función toma la propiedad behavior como argumento y retorna el color de fondo correspondiente según el valor usando la sentencia switch. La propiedad behavior retornará un color de fondo transparent si no coincide con los casos especificados.

Incorporar esta función en el objeto de estilos del componente:

// Child component - `Notification`
const Notification = (props) => (
  <>
    {/* Step 2, : Apply default styles using inline styles */}
    {/* Step 4, : Apply the value for the `background-color` property 
    based on the `behavior` prop */}
    <p
      style={{
        ...notificationStyles,
        backgroundColor: setBackgroundColor(props.behavior),
      }}
    >
      {props.text}
    </p>
  </>
);

Se utilizan convenciones de JavaScript para asegurar la estructura adecuada del objeto de estilos. Primero, se expande el objeto existente notificationStyles. Luego, se introduce una propiedad adicional, backgroundColor, cuyo valor se deriva de la cadena retornada por la función setBackgroundColor.

Código completo de la aplicación:

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 3
some-alt