[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
Controlled props is the prop that component let user fully control.
<input />'s
valueprop.
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;
相关文章推荐
- [Recompose] Make Reusable React Props Streams with Lenses
- [Recompose] Create Stream Behaviors to Push Props in React Components with mapPropsStream
- [React] Recompose: Theme React Components Live with Context
- React--Components and Props(组件和属性组件)
- React中文文档之Components and Props
- [React] Styling React Components With Aphrodite
- [Recompose] Refactor React Render Props to Streaming Props with RxJS and Recompose
- [React] Style a React component with styled-components
- [React] Style the body element with styled-components and "injectGlobal"
- [React] Public Class Fields with React Components
- [React] Use Prop Collections with Render Props
- [React] Theme your application with styled-components and "ThemeProvider"
- [Recompose] Compose Streams of React Props with Recompose’s compose and RxJS
- React 笔记4:Components and Props
- React中文文档之Components and Props
- Make interesting things with react!
- [React] Validate Custom React Component Props with PropTypes
- [React] Animate your user interface in React with styled-components and "keyframes"
- 前端框架React - Components and Props
- [React] Create component variations in React with styled-components and "extend"