Застосування Inline-стилів на Практиці
Створимо універсальний компонент Notification, який відображає текст і динамічно змінює властивість background-color залежно від пропса behavior. Реалізацію розглянемо покроково.
Крок 1
Починаємо зі створення батьківського компонента App та дочірнього компонента Notification, використовуючи базову структуру 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 />);
Крок 2
Щоб надати стандартне стилізування для компонента Notification, створюємо об'єкт з назвою notificationStyles і призначаємо йому такі властивості:
padding зі значенням "20px";
fontSize зі значенням "24px";
color зі значенням "aquamarine";
// Define default styles as an object
const notificationStyles = {
padding: "20px",
fontSize: "24px",
color: "aquamarine",
};
Призначаємо об'єкт notificationStyles як значення для атрибута style компонента Notification component, який застосовується до повернутого елемента p.
// Child component - Notification
const Notification = (props) => (
<>
{/* Step 2: Apply default styles using inline styles */}
<p style={notificationStyles}></p>
</>
);
Крок 3
У компоненті App можна використати компонент Notification, передаючи пропси behavior та text. Проп behavior визначає вигляд сповіщення, а проп text задає текст, який буде відображатися у сповіщенні.
// 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" />
</>
);
Крок 4
Можна реалізувати логіку для задання кольору фону кожного повідомлення залежно від пропса behavior наступним чином:
- Якщо значення
behavior—"positive", фон має бутиgreen; - Якщо значення
behavior—"negative", фон має бутиred; - Якщо значення
behavior—"neutral", фон має бутиblue.
Можна створити функцію для обробки цієї логіки, використовуючи оператор switch у JavaScript. Ось приклад реалізації:
// 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";
}
};
Ця функція приймає проп behavior як аргумент і повертає відповідний колір фону залежно від значення, використовуючи оператор switch. Якщо значення пропса behavior не співпадає з жодним із зазначених випадків, буде повернуто прозорий фон (transparent).
Впровадимо цю функцію у стилізований об'єкт компонента:
// 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>
</>
);
Використовуються конвенції JavaScript для забезпечення правильної структури об'єкта стилів. Спочатку розгортається існуючий об'єкт notificationStyles. Далі додається додаткова властивість backgroundColor, значення якої визначається рядком, що повертається функцією setBackgroundColor.
Повний код застосунку:
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
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
Застосування Inline-стилів на Практиці
Свайпніть щоб показати меню
Створимо універсальний компонент Notification, який відображає текст і динамічно змінює властивість background-color залежно від пропса behavior. Реалізацію розглянемо покроково.
Крок 1
Починаємо зі створення батьківського компонента App та дочірнього компонента Notification, використовуючи базову структуру 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 />);
Крок 2
Щоб надати стандартне стилізування для компонента Notification, створюємо об'єкт з назвою notificationStyles і призначаємо йому такі властивості:
padding зі значенням "20px";
fontSize зі значенням "24px";
color зі значенням "aquamarine";
// Define default styles as an object
const notificationStyles = {
padding: "20px",
fontSize: "24px",
color: "aquamarine",
};
Призначаємо об'єкт notificationStyles як значення для атрибута style компонента Notification component, який застосовується до повернутого елемента p.
// Child component - Notification
const Notification = (props) => (
<>
{/* Step 2: Apply default styles using inline styles */}
<p style={notificationStyles}></p>
</>
);
Крок 3
У компоненті App можна використати компонент Notification, передаючи пропси behavior та text. Проп behavior визначає вигляд сповіщення, а проп text задає текст, який буде відображатися у сповіщенні.
// 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" />
</>
);
Крок 4
Можна реалізувати логіку для задання кольору фону кожного повідомлення залежно від пропса behavior наступним чином:
- Якщо значення
behavior—"positive", фон має бутиgreen; - Якщо значення
behavior—"negative", фон має бутиred; - Якщо значення
behavior—"neutral", фон має бутиblue.
Можна створити функцію для обробки цієї логіки, використовуючи оператор switch у JavaScript. Ось приклад реалізації:
// 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";
}
};
Ця функція приймає проп behavior як аргумент і повертає відповідний колір фону залежно від значення, використовуючи оператор switch. Якщо значення пропса behavior не співпадає з жодним із зазначених випадків, буде повернуто прозорий фон (transparent).
Впровадимо цю функцію у стилізований об'єкт компонента:
// 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>
</>
);
Використовуються конвенції JavaScript для забезпечення правильної структури об'єкта стилів. Спочатку розгортається існуючий об'єкт notificationStyles. Далі додається додаткова властивість backgroundColor, значення якої визначається рядком, що повертається функцією setBackgroundColor.
Повний код застосунку:
Дякуємо за ваш відгук!