代码之家  ›  专栏  ›  技术社区  ›  HalfWebDev

静态方法的用例[关闭]

  •  -2
  • HalfWebDev  · 技术社区  · 6 年前

    我再加一个。React有复合组分的概念。

    class Toggle extends React.Component {
    
      static On = ({on, children}) => (on ? children : null)
      static Off = ({on, children}) => (on ? null : children)
      static Button = ({on, toggle, ...props}) => (
        <Switch on={on} onClick={toggle} {...props} />
      )
      state = {on: false}
      toggle = () =>
        this.setState(
          ({on}) => ({on: !on}),
          () => this.props.onToggle(this.state.on),
        )
      render() {
        return React.Children.map(this.props.children, child =>
          React.cloneElement(child, {
            on: this.state.on,
            toggle: this.toggle,
          }),
        )
      }
    }
    

    用法

    return (
        <Toggle onToggle={onToggle}>
          <Toggle.On>The button is on</Toggle.On>
          <Toggle.Off>The button is off</Toggle.Off>
          <Toggle.Button />
        </Toggle>
      )
    

    注意

    2 回复  |  直到 6 年前
        1
  •  1
  •   nicholaswmin    6 年前

    在ES6类中使用静态方法的所有实用且频繁的用例是什么?

    与实例无关的实用函数。

    举个例子:

    class Car {
       constructor() {
         this.steeringWheel = new SteeringWheel()
       }
    
       // Obviously can't be a static method, it deals
       // with THIS car's steering wheel.
       turn(direction) {
         this.steeringWheel.turn(direction)
       }
    
       // Can be static.
       static milesToKm(miles) {
         return miles / 0.6
       }
    }
    
    • milesToKm 没有实例化任何东西,即 Car.milesToKm(100) 作品。我不需要创建 Car

    • 方法本身从不接触实例。

        2
  •  -1
  •   Nikita Malyschkin    6 年前

    在ES6类中使用静态方法的所有实用且频繁的用例是什么?

    共享的单例实例,如队列或websocket连接。