繁体   English   中英

对复选框和无线电组件做出反应

[英]react hoc for checkbox and radio component

我正在构建我自己的复选框和无线电组件,以便我可以一遍又一遍地重复使用它。

它会是这样的

import React, { Component } from 'react'
export class Checkbox extends Component {
    render() {
        return (
            <input type={this.props.type === 'checkbox' ? 'checkbox' : 'radio'} placeholder={this.props.label} />
        )
    }
}

如果我想要一个“复选框”,我可以像这样使用它<Checkbox type="checkbox" label="My checkbox" />

如果我想要一个“复选框”,我可以像这样使用它<Checkbox type="radio" label="My checkbox" />

但是在这种情况下如何使用 HOC 改进上述解决方案? 我得到了“创建一个高阶组件,为每个组件包装公共组件”的反馈。 从上面的实现来看,在这里使用 HOC 甚至有意义吗? 如果 HOC 是必须的要求,它会是什么样子?

您不需要创建 HOC。 您只是返回输入元素。 但是 HOC 的使用方式类似于 mixin:

const NewComponent = (BaseComponent) => {
  // ... create new component from old one and update
  return UpdatedComponent
}

请参阅此博客源以更好地了解 HOC。


为了更好地改进您的组件,您可以这样做:

import React, { Component } from 'react'
export class Checkbox extends Component {
    render() {
      const { type, label } = this.props
        return (
            <input type={type} placeholder={label} />
        )
    }
}

现在,您可以根据需要简单地传递类型和标签:

<Checkbox type="radio" label="The label" />
<Checkbox type="checkbox" label="The label" />

或者,如果您想默认使用checkbox ,那么您可以像这样定义默认值:

Checkbox.defaultProps = {
  type: 'checkbox',
  label: 'The default label'
}

现在,如果您像这样使用组件:

<Checkbox />

这将呈现<input type="checkbox" label="The default label" />

有关默认道具的更多信息,请参阅文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM