对复选框和无线电组件做出特殊反应 [英] react hoc for checkbox and radio component
问题描述
我正在构建自己的复选框和广播组件,以便可以一遍又一遍地重复使用它.
I'm building my own checkbox and radio component, so that I can reuse it over and over again.
会是这样
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" />
I can use it like this if I want a "checkbox"
<Checkbox type="checkbox" label="My checkbox" />
如果我想要一个复选框",则可以像这样使用它
<Checkbox type="radio" label="My checkbox" />
I can use it like this if I want a "checkbox"
<Checkbox type="radio" label="My checkbox" />
但是在这种情况下如何使用HOC改善上述解决方案?我收到了创建一个包含每个组件的通用组件的高阶组件"的反馈.从上面的实现中,在这里使用HOC甚至有意义吗?如果HOC是必须的要求,它将是什么样?
But how to improve above solution using HOC in this case? I got feedback of "create a higher order component that wraps the common component for each." from above implementation, does it even make sense to use HOC here? if HOC is a must requirement what will it looks like?
推荐答案
您无需创建HOC.您只是在返回输入元素.但是HOC的使用就像mixin:
You don't need to create HOC. You're simply returning input element. But HOCs are used like mixin:
const NewComponent = (BaseComponent) => {
// ... create new component from old one and update
return UpdatedComponent
}
请参见以下博客源更好地了解HOC.
See this blog source to understand HOC better.
要更好地改善组件,您可以这样做:
To improve your component a little better, you can do just like this:
import React, { Component } from 'react'
export class Checkbox extends Component {
render() {
const { type, label } = this.props
return (
<input type={type} placeholder={label} />
)
}
}
现在,您只需根据需要传递类型和标签:
Now, you can simply pass type and label as required:
<Checkbox type="radio" label="The label" />
<Checkbox type="checkbox" label="The label" />
或者,如果要默认使用checkbox
,则可以定义如下默认值:
Or, if you want to use checkbox
by default, then you can define the defaults like this:
Checkbox.defaultProps = {
type: 'checkbox',
label: 'The default label'
}
现在,如果您像这样使用组件:
Now, if you use the component just like this:
<Checkbox />
这将呈现<input type="checkbox" label="The default label" />
.
有关默认道具的更多信息,请参见 doc .
For more information on default props, see the doc.
这篇关于对复选框和无线电组件做出特殊反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!