返回

React 通知:打造美观实用的消息提醒组件

前端







## React 通知组件:让消息提醒更生动

### 1. 项目设置

首先,使用create-react-app创建一个新的React项目。这将为您提供一个预先配置好的开发环境,可以立即开始编码。

npx create-react-app react-notification
cd react-notification
npm start


### 2. 安装样式库

接下来,安装一个CSS模块化库,以便以更清晰的方式组织样式。我们推荐使用styled-components。

npm install --save styled-components


### 3. 编写 Notification 组件

现在,让我们创建一个新的组件Notification,它将负责显示和隐藏消息。在src目录下新建一个Notification.js文件,并添加以下代码:

```javascript
import styled from "styled-components";

const Notification = ({ message, type }) => {
  const notificationType = type ? type : "info";
  return (
    <div className={`notification ${notificationType}`}>
      <p>{message}</p>
      <button onClick={() => {}}>X</button>
    </div>
  );
};

export default Notification;

4. 编写样式

在src目录下新建一个styles.css文件,并添加以下CSS样式:

.notification {
  position: relative;
  padding: 16px;
  margin-bottom: 10px;
  border-radius: 4px;
  animation: slideInUp 0.3s ease-in;
}

.notification.info {
  background-color: #2196f3;
  color: white;
}

.notification.success {
  background-color: #4caf50;
  color: white;
}

.notification.warning {
  background-color: #ffc107;
  color: black;
}

.notification.error {
  background-color: #f44336;
  color: white;
}

.notification button {
  position: absolute;
  top: 0;
  right: 0;
  padding: 5px 10px;
  border-radius: 50%;
  background-color: #8d8d8d;
  color: white;
  cursor: pointer;
}

@keyframes slideInUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

5. 使用 Notification 组件

现在,您可以将Notification组件导入到需要显示消息的地方。例如,如果您有一个名为App.js的文件,则可以添加以下代码:

import Notification from "./Notification";

const App = () => {
  const [notifications, setNotifications] = useState([]);

  const addNotification = (message, type) => {
    setNotifications([...notifications, { message, type }]);
  };

  const removeNotification = (index) => {
    const newNotifications = notifications.filter((n, i) => i !== index);
    setNotifications(newNotifications);
  };

  return (
    <div className="App">
      <h1>React Notification</h1>
      <button onClick={() => addNotification("Hello World!", "success")}>Add Notification</button>
      {notifications.map((notification, index) => (
        <Notification key={index} message={notification.message} type={notification.type} />
      ))}
    </div>
  );
};

export default App;

6. 运行项目

现在,您可以运行项目并查看Notification组件是否正常工作。在命令行中输入以下命令:

npm start

打开浏览器,访问http://localhost:3000,您应该会看到一个带有按钮的页面。单击按钮以添加通知,您应该会看到一个新的通知从底部滑入。单击通知右上角的X按钮以将其删除。

7. 结语

现在,您已经创建了一个美观实用的React通知组件,它具有渐入渐出的动画效果,可以轻松集成到您的应用程序中。通过使用CSS模块化和styled-components,您还可以轻松地对样式进行调整,以匹配您的应用程序的主题。希望这篇文章对您有所帮助!