[React] Use Prop Collections with Render Props

本文介绍了一种在React中使用Render Props模式时收集常用属性的方法。通过创建一个包含所有必要属性的对象,可以方便地将其应用于多个组件。文章还讨论了如何使用aria-pressed属性来实现按钮的切换状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 the button 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 aria-pressed="true" is used the button is a toggle button that is currently pressed.
  • if aria-pressed="mixed" is used, the button is considered to be partially pressed.

转载于:https://www.cnblogs.com/Answer1215/p/9582191.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值