[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 />
'svalue
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;
相关推荐
游走的豚鼠君 2020-11-10
81417707 2020-10-30
ctg 2020-10-14
小飞侠V 2020-09-25
PncLogon 2020-09-24
jipengx 2020-09-10
颤抖吧腿子 2020-09-04
wwzaqw 2020-09-04
maple00 2020-09-02
青蓝 2020-08-26
罗忠浩 2020-08-16
liduote 2020-08-13
不知道该写啥QAQ 2020-08-02
pengruiyu 2020-08-01
wmd看海 2020-07-27
孝平 2020-07-18
Eduenth 2020-07-05
iftrueIloveit 2020-07-04