[React] Use Prop Collections with Render Props
Sometimes you have common use cases that require common props to be applied to certain elements. You can collect these props into an object for users to simply apply to their elements and we'll see how to do that in this lesson.
In short, in Render props partten, you can provide an Object, which contains all the necessary common used props or functions. Then users can just use this single object to multi elements.
// prop collections import React from 'react' import {Switch} from '../switch' class Toggle extends React.Component { state = {on: false} toggle = () => this.setState( ({on}) => ({on: !on}), () => this.props.onToggle(this.state.on), ) getStateAndHelpers() { return { on: this.state.on, toggle: this.toggle, togglerProps: { 'aria-pressed': this.state.on, onClick: this.toggle, }, } } render() { return this.props.children(this.getStateAndHelpers()) } } function Usage({ onToggle = (...args) => console.log('onToggle', ...args), }) { return ( <Toggle onToggle={onToggle}> {({on, togglerProps}) => ( <div> <Switch on={on} {...togglerProps} /> <hr /> <button aria-label="custom-button" {...togglerProps}> {on ? 'on' : 'off'} </button> </div> )} </Toggle> ) } Usage.title = 'Prop Collections' export {Toggle, Usage as default}
TogglerProps is the object we are talking about, it collect all the necessary common used props and functions send by to Render Prop, then this can be used for both <Switch> and <button>
An advantage of using role="button" is that it allows the creation of toggle buttons. A toggle button can have two states: pressed and not pressed. Whether a button is a toggle button or not can be indicated with the
aria-pressed
attribute in addition to thebutton
role:
- If
aria-pressed
is not used the button is not a toggle button.- If
aria-pressed="false"
is used the button is a toggle button that is currently not pressed.- If
is used the button is a toggle button that is currently pressed.
aria-pressed="true"
- if
aria-pressed="mixed"
is used, the button is considered to be partially pressed.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2017-09-04 [Angular & Web] Retrieve user data from Session
2016-09-04 [AngualrJS] ng-strict-di
2016-09-04 [Ramda] Simple log function for debugging Compose function / Using R.tap for logging
2015-09-04 [Flux] 2. Overview and Dispatchers
2015-09-04 [Flux] 1. Development Environment Setup
2015-09-04 [CSS] Animating SVG
2015-09-04 [Node.js] Scraping Dynamic JavaScript Websites with Nightmare