zoukankan      html  css  js  c++  java
  • [React] Use Prop Collections with Render Props

    Sometimes you have common use cases that require common props to be applied to certain elements. You can collect these props into an object for users to simply apply to their elements and we'll see how to do that in this lesson.

    In short, in Render props partten, you can provide an Object, which contains all the necessary common used props or functions. Then users can just use this single object to multi elements.

    // prop collections
    
    import React from 'react'
    import {Switch} from '../switch'
    
    class Toggle extends React.Component {
      state = {on: false}
      toggle = () =>
        this.setState(
          ({on}) => ({on: !on}),
          () => this.props.onToggle(this.state.on),
        )
      getStateAndHelpers() {
        return {
          on: this.state.on,
          toggle: this.toggle,
          togglerProps: {
            'aria-pressed': this.state.on,
            onClick: this.toggle,
          },
        }
      }
      render() {
        return this.props.children(this.getStateAndHelpers())
      }
    }
    
    function Usage({
      onToggle = (...args) => console.log('onToggle', ...args),
    }) {
      return (
        <Toggle onToggle={onToggle}>
          {({on, togglerProps}) => (
            <div>
              <Switch on={on} {...togglerProps} />
              <hr />
              <button aria-label="custom-button" {...togglerProps}>
                {on ? 'on' : 'off'}
              </button>
            </div>
          )}
        </Toggle>
      )
    }
    Usage.title = 'Prop Collections'
    
    export {Toggle, Usage as default}

    TogglerProps is the object we are talking about, it collect all the necessary common used props and functions send by to Render Prop, then this can be used for both <Switch> and <button>

    An advantage of using role="button" is that it allows the creation of toggle buttons. A toggle button can have two states: pressed and not pressed. Whether  a button is a toggle button or not can be indicated with the aria-pressed attribute in addition to the button role:

    • If aria-pressed is not used the button is not a toggle button.
    • If aria-pressed="false" is used the button is a toggle button that is currently not pressed. 
    • If aria-pressed="true" is used the button is a toggle button that is currently pressed.
    • if aria-pressed="mixed" is used, the button is considered to be partially pressed.
  • 相关阅读:
    联想电脑关闭屏幕点亮屏幕(T480为例)
    安卓手机时钟APP推荐
    电脑手机端如何互传文件、图片、网址等
    仿写一个简陋的 IOC/AOP 框架 mini-spring
    类加载之 <clinit>() 和 <init>()
    深入理解Java类加载
    Java垃圾回收
    Java内存区域(运行时数据区域)和内存模型(JMM)
    Java 泛型学习总结
    一篇文章概括 Java Date Time 的使用
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9582191.html
Copyright © 2011-2022 走看看