美文网首页React
react 写一个 switch 组件

react 写一个 switch 组件

作者: Lia代码猪崽 | 来源:发表于2021-01-05 15:22 被阅读0次
效果如图所示

App

/src/App.js

import { useState } from "react";
import Switch from "./components/Switch";
import "./App.css";

function App() {
  const [isChecked, setIsChecked] = useState(false);

  return (
    <div className="App">
      <header className="App-header">
        <Switch
          checked={isChecked}
          onChange={(checked) => {
            setIsChecked(checked);
          }}
        />
      </header>
    </div>
  );
}

export default App;

/src/App.css

.App {
  text-align: center;
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

2. Switch

/src/components/Switch/index.js

import { useEffect, useState } from "react";
import "./index.css";

function Switch({ checked, onChange, ...props }) {
  const [isChecked, setIsChecked] = useState(checked);

  useEffect(() => {
    setIsChecked(checked);
  }, [checked]);

  function onInputChange(e) {
    const value = e.target.checked;
    setIsChecked(value);
    if (!onChange) {      
      return;
    }
    onChange(value);
  }

  return (
    <label className="switch">
      <input
        type="checkbox"
        checked={isChecked}
        onChange={onInputChange}
        className="switch-checkbox"
      />
      <div
        className={ 
          isChecked
            ? "switch-container switch-container-checked" 
            : "switch-container" 
         }
      ></div>
      {isChecked ? "true" : "false"}
    </label>
  );
}

export default Switch;

/src/components/Switch/index.css

.switch{
  position: relative;
}
.switch-checkbox {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  width: 100%;
  height: 100%;
  z-index: 2;
  border: 0;
  appearance: none;
}
.switch-container {
  position: relative;
  width: 48px;
  height: 28px;
  border-radius: 28px;
  background: #a7aaa6;
  z-index: 0;
  margin: 0;
  padding: 0;
  appearance: none;
  border: 0;
  transition: all 0.3s;
}
.switch-container::after {
  position: absolute;
  left: 1px;
  top: 1px;
  width: 26px;
  height: 26px;
  border-radius: 50%;
  background-color: #fff;
  content: "";
  transition: all 0.3s;
}
.switch-container-checked {
  background-color: #4dd865;
}
.switch-container-checked::after {
  transform: translateX(20px);
}

相关文章

网友评论

    本文标题:react 写一个 switch 组件

    本文链接:https://www.haomeiwen.com/subject/rfqwoktx.html