简体   繁体   中英

Styling individual child component in React

I have a parent ButtonGroup component that takes in children like this.props.children . The children I'm passing to it is the btnItem component that renders out single buttons. We can add as many of these buttons as we want.

//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>

在此处输入图片说明

^ This is what I get out of the above code.

What I want to achieve is a way for me style the border radius of the first and last item so that they have a curved border. This would have to be dynamic as this styling will be dependent on how many children buttonItem we render.

I should also mention that I'm using styled-components for the css of each button.

you can use first and last child css pseudo selector here. in your Component write following code.

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;
     }
 `;

and render function like this

<ButtonGroupComponent>
  <buttonItem caption="Nothing"/>
  <buttonItem caption="Something" disabled={true}/>
  <buttonItem caption="Refresh"/>
</ButtonGroupComponent>

check out this demo

I wrap a quick example here, I didn't test it yet but you could try:

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...
    `}

    `

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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