Javascript 在React中设置单个子组件的样式
我有一个parentJavascript 在React中设置单个子组件的样式,javascript,css,reactjs,styled-components,Javascript,Css,Reactjs,Styled Components,我有一个parentButtonGroup组件,它接收像this.props.children这样的子对象。我传递给它的孩子是呈现单个按钮的btnItem组件。我们可以添加任意数量的按钮 //ButtonGroup Component render() { return ( <div> {this.props.children} </div> ) } //buttonItem component: render() { re
ButtonGroup
组件,它接收像this.props.children
这样的子对象。我传递给它的孩子是呈现单个按钮的btnItem
组件。我们可以添加任意数量的按钮
//ButtonGroup Component
render() {
return (
<div>
{this.props.children}
</div>
)
}
//buttonItem component:
render() {
return (
<button disabled={this.props.disabled}>{this.props.caption}</button>
)
}
//final render
<ButtonGroupComponent>
<buttonItem caption="Nothing"/>
<buttonItem caption="Something" disabled={true}/>
<buttonItem caption="Refresh"/>
</ButtonGroupComponent>
//按钮组组件
render(){
返回(
{this.props.children}
)
}
//buttonItem组件:
render(){
返回(
{this.props.caption}
)
}
//最终渲染
^这就是我从上面的代码中得到的
我想要实现的是,为我设计第一个和最后一个项目的边界半径,使它们有一个弯曲的边界。这必须是动态的,因为此样式将取决于我们渲染的子项数buttonItem
我还应该提到,我正在为每个按钮的css使用样式化组件。您可以在这里使用第一个和最后一个子css伪选择器。在组件中编写以下代码
const ButtonGroupComponent= styled.div`
button:first-child {
border-top-left-radius: 3px;
border-bottom-left-radius: 3px;
}
button:last-child {
border-top-right-radius: 3px;
border-bottom-right-radius: 3px;
}
`;
然后像这样渲染函数
<ButtonGroupComponent>
<buttonItem caption="Nothing"/>
<buttonItem caption="Something" disabled={true}/>
<buttonItem caption="Refresh"/>
</ButtonGroupComponent>
看看这个我在这里总结了一个简单的示例,我还没有测试它,但您可以尝试:
const StyledButtonGroupComponent = styled(
({ willBeStyled, children, ...rest }) =>(
<ButtonGroupComponent {...rest}>{children}</ButtonGroupComponent>
))`
${props => React.Children.toArray(props.children).length <= props.willBeStyled && `
...first child, last child styles go here...
`}
`
const StyledButtonGroupComponent=styled(
({willBeStyled,children,…rest})=>(
{儿童}
))`
${props=>React.Children.toArray(props.Children)我认为这会起作用,但它不是。有任何想法吗?我为你做了代码框演示。请检查它。如果有任何答案解决了你的问题,请考虑通过点击复选标记和上投票来接受它。这向更广泛的社区表明,你已经找到了解决方案,并给回答者和YO带来了一些声誉。你自己,没有义务这么做。