[React] Make Controlled React Components with Control Props
React with Control Make Components Props
2023-09-14 09:00:51 时间
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;
相关文章
- error: Build input file cannot be found: ‘*******/node_modules/react-native/Libraries/WebSocket/libf
- 写给vue转react的同志们(6)
- React-Navigation Integration with Redux
- react源码分析:深度理解React.Context
- react hooks 生命周期渲染时机简述
- 【Techo Day 腾讯技术开放日】jira React 实战
- 你需要的react面试高频考察点总结
- react的jsx和React.createElement是什么关系?面试常问_2023-02-27
- react源码分析:深度理解React.Context_2023-02-28
- 深度分析React源码中的合成事件_2023-03-01
- React 组件库 CSS 样式问题分析
- react进阶用法指南
- React源码分析,深入理解fiber
- 在React中使用 react-router-dom 编程式路由导航【含V5.x、V6.x】
- React的useLayoutEffect和useEffect执行时机有什么不同
- react的jsx和React.createElement是什么关系?面试常问5
- Taro+react 微信小程序记录
- React源码分析(二)渲染机制_2023-02-19
- React/ReactNative 状态管理: redux-toolkit 如何使用
- ORA-39322: Cannot use transportable tablespace with TIMESTAMP WITH TIME ZONE columns and different time zone version. ORACLE 报错 故障修复 远程处理
- React 许可证虽严苛,但不必过度 react
- 探索React框架中MySQL数据库的应用(react mssql)