您的位置:首页 > Web前端 > React

[React] Make Controlled React Components with Control Props

2017-12-15 01:48 453 查看
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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: