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.

    We have 'button' and 'Switch' component which shares same attrs:

        <Toggle
            onToggle={(on) => console.log("Toggle", on)}
            render={({on, toggle}) => (
                <div>
                    {on
                        ? 'The button is on'
                        : 'The button is off'
                    }
                    <Switch on={on} onClick={toggle} aria-expanded={on}/>
                    <hr />
                    <button onClick={toggle} aria-expanded={on}>
                        {on ? 'on': 'off'}
                    </button>
                </div>
            )}
        />;

    We can pass the same props from the render props:

        <Toggle
            onToggle={(on) => console.log("Toggle", on)}
            render={({on, toggle, toggleProps}) => (
                <div>
                    {on
                        ? 'The button is on'
                        : 'The button is off'
                    }
                    <Switch on={on} {...toggleProps} />
                    <hr />
                    <button {...toggleProps}>
                        {on ? 'on': 'off'}
                    </button>
                </div>
            )}
        />;
    import React from 'react';
    
    class Toggle extends React.Component {
    
      // An empty function
      static defaultProps = {onToggle: () => {}};
    
      // default state value
      state = {on: false};
    
      // toggle method
      toggle = () =>
        this.setState(
          ({on}) => ({on: !on}),
          () => {
            this.props.onToggle(this.state.on)
          }
        );
    
      render() {
        return this.props.render({
            on: this.state.on,
            toggle: this.toggle,
            toggleProps: {
                'aria-expanded': this.state.on,
                onClick: this.toggle,
            }
        });
      }
    }
    
    export default Toggle;
  • 相关阅读:
    LVS/NAT 配置
    LVS 介绍
    Nagios 服务安装
    Mysql 主从复制搭建
    GitHub托管BootStrap资源汇总
    基于bootstrap的datatable控件
    微信在线客服系统-微信公众平台开发
    UI Prototype Design IDE( 界面原型设计工具 )
    vlc多功能播放器
    javaC#php主流语言实现FMS流媒体传输协议RTMP的开源组件
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8035752.html
Copyright © 2011-2022 走看看