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

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

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;

 

转载于:https://www.cnblogs.com/Answer1215/p/8041059.html

你可能感兴趣的文章
MYSQL 日期函数
查看>>
Oracle触发器之替代触发器
查看>>
NodeJS基础教程之一
查看>>
你真的了解SDWebImage吗?
查看>>
BZOJ 1101 Luogu P3455 POI 2007 Zap (莫比乌斯反演+数论分块)
查看>>
C#嵌套类
查看>>
2017《面向对象程序设计》课程作业三
查看>>
[HDU] 1068 Girls and Boys(二分图最大匹配)
查看>>
ADO.NET类的模型关系图
查看>>
SRM 604 DIV2 250
查看>>
python中异常处理之esle,except,else
查看>>
看苹果官方API
查看>>
06-基础-系统指令-v-model-语法糖原理
查看>>
论文网站相关链接
查看>>
死锁,死锁必要条件及处理策略
查看>>
Kinect for windows
查看>>
Java EE Map
查看>>
Hadoop源代码点滴-文件系统HDFS
查看>>
单个页面Request编码方式的改变,无需改动Web.config~
查看>>
SQL Server中的窗口函数
查看>>