zoukankan      html  css  js  c++  java
  • [React] Make Controlled React Components with Control Props

    Sometimes users of your component want to have more control over what the internal state is. In this lesson we'll learn how to allow users to control some of our component’s state just like the <input />'s value prop.

    Controlled props is the prop that component let user fully control.

    import React from 'react';
    
    class Toggle extends React.Component {
    
        // An empty function
        static defaultProps = {
            defaultOn: false,
            onToggle: () => {
            }
        };
    
        // default state value
        initialState = {on: this.props.defaultOn};
        state = this.initialState;
    
        isControlled() {
            return this.props.on !== undefined;
        }
    
        // toggle method
        toggle = () =>{
          if (this.isControlled()) {
            this.props.onToggle(!this.props.on)
          } else {
              this.setState(
                  ({on}) => ({on: !on}),
                  () => {
                      this.props.onToggle(this.state.on)
                  }
              );
          }
        };
    
    
        reset = () => this.setState(
            this.initialState
        );
    
        render() {
            return this.props.render({
                on: this.isControlled() ?
                        this.props.on :
                        this.state.on,
                toggle: this.toggle,
                reset: this.reset,
                getProps: (props) => {
                    return {
                        'aria-expanded': this.state.on,
                        role: 'button',
                        ...props
                    };
                }
            });
        }
    }
    
    export default Toggle;
  • 相关阅读:
    20165222第八周课上补做
    20165222—第八周学习
    20165222《Java程序设计》——实验二 面向对象程序设计
    20165222 结对编程学习
    20165222 第七周学习总结
    20165222 第六周学习总结
    20165222 实验一java开发环境的熟悉
    20165222 第五周学习总结
    JSP
    Servlet
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8041059.html
Copyright © 2011-2022 走看看