[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.

 

We have 'button' and 'Switch' component which shares same attrs:

复制代码
    <Toggle
        onToggle={(on) => console.log("Toggle", on)}
        render={({on, toggle}) => (
            <div>
                {on
                    ? 'The button is on'
                    : 'The button is off'
                }
                <Switch on={on} onClick={toggle} aria-expanded={on}/>
                <hr />
                <button onClick={toggle} aria-expanded={on}>
                    {on ? 'on': 'off'}
                </button>
            </div>
        )}
    />;
复制代码

 

We can pass the same props from the render props:

复制代码
    <Toggle
        onToggle={(on) => console.log("Toggle", on)}
        render={({on, toggle, toggleProps}) => (
            <div>
                {on
                    ? 'The button is on'
                    : 'The button is off'
                }
                <Switch on={on} {...toggleProps} />
                <hr />
                <button {...toggleProps}>
                    {on ? 'on': 'off'}
                </button>
            </div>
        )}
    />;
复制代码
复制代码
import React from 'react';

class Toggle extends React.Component {

  // An empty function
  static defaultProps = {onToggle: () => {}};

  // default state value
  state = {on: false};

  // toggle method
  toggle = () =>
    this.setState(
      ({on}) => ({on: !on}),
      () => {
        this.props.onToggle(this.state.on)
      }
    );

  render() {
    return this.props.render({
        on: this.state.on,
        toggle: this.toggle,
        toggleProps: {
            'aria-expanded': this.state.on,
            onClick: this.toggle,
        }
    });
  }
}

export default Toggle;
复制代码

 

posted @   Zhentiw  阅读(149)  评论(0编辑  收藏  举报
编辑推荐:
· 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工具
历史上的今天:
2016-12-14 [JS Compse] 4. A collection of Either examples compared to imperative code
2015-12-14 [AngularJS] Services, Factories, and Providers -- value & Providers
2015-12-14 [AngularJS] Services, Factories, and Providers -- Service vs Factory
2014-12-14 [MongoDB] Query, update, index and group
点击右上角即可分享
微信分享提示