2017-06-20 54 views
2

是否有可能使用伪类作为样式组件。我有复选框应该显示SVG图像:选中/未选中显示状态为选中/未选中。我可以通过父母传递道具来做到这一点。但是我被告知只有css(风格化的组件)才有可能。我的代码 部分:ReactJS +样式组件+伪类

const CheckboxInput = styled.input` 
    &:checked, &:not(:checked) { 
    display: none; 
}`; 

const CheckboxLabel = styled.label` 
    cursor: pointer; 
    -webkit-user-select: none; /* Chrome/Safari */ 
    -moz-user-select: none; /* Firefox */ 
    -ms-user-select: none; /* IE10+ */ 
`; 

function Checkbox(props) { 
    return (
    <CheckboxLabel htmlFor="id" onChange={() => { props.onchange(); }}> 
     <CheckboxInput id="id" type="checkbox" checked={props.checked} value="cb" name="cb" /> 
     <Span><SVG glyph={checked} width={17} height={17} /></Span> 
     <Span><SVG glyph={unchecked} width={17} height={17} /></Span> 
     {props.children} 
    </CheckboxLabel> 
); 
} 

回答

2

随着styled-components以下的选择,你可以使用输入/复选框的状态来修改样式仅适用于CSS:

&:checked + ${Label} { 
    /* your CSS */ 
    } 

下面是一个完整的例子:

import React from 'react'; 
import { render } from 'react-dom'; 
import styled from 'styled-components'; 


const Label = styled.label` 
    background: red; 
    display: block; 
    padding: 1rem; 
`; 

const Input = styled.input` 
    &:checked + ${Label} { 
    background: blue; 
    } 
`; 

const App =() => (
    <div> 
    <Input id="input" type="checkbox" /> 
    <Label for="input" /> 
    </div> 
); 

render(<App />, document.getElementById('root')); 

这里你可以看到它的预览:https://codesandbox.io/s/oYQ21A4wz

这应该给你一个基本的想法,如何只用CSS来改变样式。

+0

这位先生!谢谢 – spences10