无法在javascript反应中更改警报消息的颜色
Posted
技术标签:
【中文标题】无法在javascript反应中更改警报消息的颜色【英文标题】:Not Able to Change the Color of the alert Message in javascript react 【发布时间】:2021-10-26 03:17:41 【问题描述】:我正在尝试对警报组件进行编程,但我无法更改警报消息的颜色。
当我在导航栏中启用暗模式时,它会显示一条警报消息(在导航栏组件代码的最后出现)。我正在使用引导 CSS
警报组件:
import React from "react";
export default function Alert(props)
const capital = (word) =>
const lower = word.toLowerCase();
return lower.charAt(0).toUpperCase() + lower.slice(1);
;
return (
props.alert && (
<div
className=`alert alert-$props.alert.type alert-dismissible fade show`
role="alert"
>
<strong>capital(props.alert.type)</strong>: props.alert.msg
</div>
)
);
导航栏组件:
import React from "react";
import PropTypes from "prop-types";
export default function Navbar(props)
return (
<>
<nav
className=`navbar navbar-expand-lg navbar-$props.mode bg-$props.mode`
>
<div className="container-fluid">
<a className="navbar-brand" href="/">
Navbar
</a>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav me-auto mb-2 mb-lg-0">
<li className="nav-item">
<a className="nav-link active" aria-current="page" href="/">
Home
</a>
</li>
<li className="nav-item">
<a className="nav-link" href="/">
Link
</a>
</li>
<li className="nav-item">
<a
className="nav-link "
href="/"
tabIndex="-1"
aria-current="page"
>
props.aboutText
</a>
</li>
</ul>
<form className="d-flex mx-2">
<input
className="form-control me-2"
type="search"
placeholder="Search"
aria-label="Search"
/>
<button className="btn btn-outline-success" type="submit">
Search
</button>
</form>
<div
className=`form-check form-switch text-$
props.mode === "light" ? "dark" : "light"
mx-2`
>
<input
className="form-check-input "
onClick=props.togglemode
type="checkbox"
id="flexSwitchCheckDefault"
/>
<label
className=`form-check-label `
htmlFor="flexSwitchCheckDefault"
>
Enable Dark Mode
</label>
</div>
</div>
</div>
</nav>
</>
);
App.js:
import "./App.css";
import Navbar from "./components/Navbar";
import React, useState from "react";
import Alert from "./components/Alert";
function App()
const [mode, setMode] = useState("light");
const [alert, setAlert] = useState(null);
const showAlert = (message, type) =>
setAlert(
msg: message,
type: type,
);
setTimeout(() =>
setAlert(null);
, 1500);
;
const togglemode = () =>
if (mode === "light")
setMode("dark");
document.body.style.backgroundColor = "#042743";
showAlert("Dark mode has been enabled", "Success");
else
setMode("light");
document.body.style.backgroundColor = "white";
showAlert("Light mode has been enabled", "Success");
;
return (
<>
<Navbar aboutText="About Myself" mode=mode togglemode=togglemode />
<div className="container " my-3="true">
<Alert alert=alert />
</div>
</>
);
export default App;
【问题讨论】:
【参考方案1】:更改 showAlert 函数第二个属性:
从“成功”到“成功”。它会起作用的。
为了方便您,替换:
showAlert("Dark mode has been enabled", "Success");
与:
showAlert("Dark mode has been enabled", "success");
在切换模式功能的两个地方。
【讨论】:
以上是关于无法在javascript反应中更改警报消息的颜色的主要内容,如果未能解决你的问题,请参考以下文章