2017-06-20 46 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