博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[React] Make Controlled React Components with Control Props
阅读量:6238 次
发布时间:2019-06-22

本文共 1458 字,大约阅读时间需要 4 分钟。

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;

 

转载地址:http://dcdia.baihongyu.com/

你可能感兴趣的文章
STL UVA 11991 Easy Problem from Rujia Liu?
查看>>
模拟 URAL 1149 Sinus Dances
查看>>
Oracle 11G 数据库迁移【expdp/impdp】
查看>>
17.EXTJs 中icon 与iconCls的区别及用法!
查看>>
3.mybatis实战教程(mybatis in action)之三:实现数据的增删改查
查看>>
Caused by: Unable to load bean: type: class:com.opensymphony.xwork2.ObjectFactory - bean - jar
查看>>
让你拥有超能力:程序员应该掌握的统计学公式
查看>>
互联网组织的未来:剖析 GitHub 员工的任性之源
查看>>
Java 开源博客 Solo 1.4.0 发布 - 简化
查看>>
Oracle巡检
查看>>
【转载】胜者树
查看>>
查看mysql数据库存放的路径|Linux下查看MySQL的安装路径
查看>>
selenium+testNG+Ant
查看>>
1024程序员节,你屯书了吗?(内含福利)
查看>>
移动端JS 触摸事件基础
查看>>
Flex拖动原来如此简单
查看>>
温故而知新:什么是wcf
查看>>
centos语言设置
查看>>
php安装
查看>>
Fragment在getUserVisibleHint时进行加载数据的问题记录
查看>>