Day 27 建立 Switch

实作

import React, { useState } from 'react';
import propTypes from 'prop-types';
import styled from 'styled-jss';

const StyledSwitch = styled('input')({
    opacity: 0,
    width: 0,
    height: 0,
});

const StyledSwitchContainer = styled('label')({
    width: 40,
    height: 20,
    borderRadius: 40,
    display: 'block',
    cursor: 'pointer',
    position: 'relative',
    transition: 'background-color .2s ease',
    backgroundColor: ({ theme: { colors }, active }) => active ? colors.grey1 : colors.primary
})

const StyledIndicator = styled('span')({
    width: 16,
    height: 16,
    marginTop: 2,
    borderRadius: 20,
    display: 'inline-block',
    transition: 'margin-left .2s ease',
    boxShadow: '0px 0px 2px rgba(0, 0, 0, 0.7)',
    marginLeft: ({ active }) => active ? 22 : 2,
    backgroundColor: ({ theme }) => theme.colors.white,
});

const onSwitchClick = ({ active, onClick, setActive }) => e => {
    setActive(!active);
    onClick(e);
}

const Switch = ({ onClick, ...props }) => {
    const [active, setActive] = useState(false)
    const handleOnClick = onSwitchClick({ active, onClick, setActive });

    return (<StyledSwitchContainer active={active}  >
        <StyledIndicator active={active} />
        <StyledSwitch {...props} type='checkbox' value={active} onClick={handleOnClick} />
    </StyledSwitchContainer>)
};

Switch.propTypes = {
    onClick: propTypes.func
}

Switch.defaultProps = {
    onClick: () => false
}

export default Switch;

Usage

import React, { Fragment } from "react";
import theme from "../../lib/theme";
import Switch from "../../lib/Switch";
import ThemeProvider from "../../lib/ThemeProvider";

const Provider = (props) => {
  return <ThemeProvider theme={theme}>{props.children}</ThemeProvider>;
};

const Template = args => {
  return (
      <Provider>
        <Fragment>
            <Switch />
        </Fragment>
      </Provider>
  );
}

export const Default = Template.bind({});

export default {
  component: Switch,
  title: "Form/Switch",
};

结果如下:


<<:  Equal Sides Of An Array

>>:  菜鸡用 Phaser 拾起童年游戏 29

IOS、Python自学心得30天 Day-12 模组训练改善-4

前言: 利用while True:的方法後,已经能够以少次数的 epochs 来重复储存模型,但至於...

延伸(1)-ML接入团队的原本开发生态 | ML#Day29

背景提要 团队走DevOps文化,所以频繁地沟通理解,以及任何东西考虑对於系统的定位,已经是我们再熟...

什麽是AutoML

什麽是AutoML 根据 Microsoft的说法节录如下: 自动化机器学习 (亦称为自动化 ML ...

Day05 补充笔记1

在 React 中使用的语法 JSX有一些使用规则: 当我们将网页切割成数个Component时,定...

React Custom hook 踩坑日记 - useFetch

今天分享一个get API的自定义hook做法,这个hook可以依据不同需求去做调整,我只是提供了做...