在 ReactJs 中实现一个 ButtonToggleGroupComponent
Posted
技术标签:
【中文标题】在 ReactJs 中实现一个 ButtonToggleGroupComponent【英文标题】:Implement a ButtonToggleGroupComponent in ReactJs 【发布时间】:2018-05-14 18:51:37 【问题描述】:我对反应很陌生,我想实现一个简单的 ButtonToggleComponent 和一个 ButtonToggleGroupComponent。第二个组件包含 n 个 ButtonToggleComponents 并且有一些逻辑。 ButtonToggleGroupComponent 应该只允许一个 ButtonToggleComponent 像单选控件的行为一样同时处于活动状态。此外,第一个和最后一个 ButtonToggleComponent 不应像我用于此组件的 material-button 那样在一侧有圆角。
我的方法:
ButtonToggleComponent:
class ButtonToggleComponent extends React.Component
_label;
_isFirst;
_isLast;
_classes;
constructor(label, isFirst, isLast, classes)
super();
this._label = label;
this._isFirst = isFirst;
this._isLast = isLast;
this._classes = classes;
get Label()
return this._label;
get IsFirst()
return this._isFirst;
get IsLast()
return this._isLast;;
get Classes()
return this._classes;
getCorrectCornerStyles()
if(this.IsFirst)
return
borderTopRightRadius: "0",
borderBottomRightRadius: "0"
else if(this.IsLast)
return
borderBottomLeftRadius: "0",
borderTopLeftRadius: "0"
render()
return <Button raised color="primary" className="buttonToggle" style=this.getCorrectCornerStyles()>
<label className=this.Classes.buttonLabel>this.Label</label>
</Button>
ButtonToggleGroupComponent:
class ButtonToggleGroupComponent extends React.Component
_buttonToggleChildren;
_classes;
constructor( children, classes )
super();
this._buttonToggleChildren = children;
this._classes = classes;
get ButtonToggleChildren()
return this._buttonToggleChildren;
get Classes()
return this._classes;
render()
return <div>
this.ButtonToggleChildren
</div>
使用方法:
<ButtonToggleGroupComponent>
<ButtonToggleComponent isFirst=true label="a" />
<ButtonToggleComponent isLast=true label="s" />
</ButtonToggleGroupComponent>
显示:
如您所见,我将两个道具(isFirst、isLast)传递给 ButtonToggleComponent,我可以使用它们为角落应用正确的样式,但我认为这不是最干净的解决方案,或者换句话说,不是最佳实践解决方案。我怎么能在不传递道具的情况下做到这一点?因为每次我必须应用这些样式的第一个和最后一个 ButtonToggleGroupComponent 。还是我应该完全不同?
另外,我不知道如何实现始终只有一个 ButtonToggleComponent 可以处于活动状态的功能。一点背景知识:这是一个新项目,我想先设计组件,然后再开始状态管理(我们想使用 redux)并创建操作和类似的东西。因此,如果该组件能够执行此功能,即只有 ButtonToggleComponent 可以在没有状态的情况下同时处于活动状态,那就太好了。这可能吗?
如果您发现其他可以做得更好的事情,请随时提及。这对我来说非常有价值。
【问题讨论】:
【参考方案1】:你可以在你的容器中使用 React.Children,它允许你为容器中的组件设置样式,你仍然需要你不需要手动输入的道具。这还允许您向父类添加其他属性等自定义项,并且可以将它们传递给内部的所有按钮。
类似:
React.Children.map(this.props.children, (child, index) => (
if(index === 0)
React.cloneElement(
child,
isFirst
)
else if (index === React.Children.count - 1)
// Same as above but with isLast
else
React.cloneElement(child);
))
编辑:虽然您尝试执行的操作有点冗长,但最好使用 css 属性(:last-child
和 :first-child
)来执行此操作。
【讨论】:
是否可以在 JSS 中使用这些 css 属性?因为我想使用Material-UI CSS in JS 功能来设置我的组件的样式。你知道吗?以上是关于在 ReactJs 中实现一个 ButtonToggleGroupComponent的主要内容,如果未能解决你的问题,请参考以下文章
是否可以使用 IDP 独立代码在 ReactJS 中实现 open id connect SSO?
在 reactjs 中实现基于 INTERFACE 的功能以基于变量呈现组件