CSS

21.12.15 특정 컴포넌트에 props에 따라 css 색 변경

슈팅스타제제 2021. 12. 15. 12:44

css 속성 하나만 바꿀 경우 

1. interface에서 사용할 props의 타입을 정의해주고 

2. 사용할 styled component를 정의하는 부분에서 조건식을 적용할  Props를 넘겨준다. 

3. 렌더링 부에서는 상태 함수와 클릭 이벤트 함수를 정의하고 컴포넌트를 리턴할 때 props에 상태값을 넘겨준다. 

//SelectedBtnPag.tsx

interface SelectedProps {
	isSelected: boolean
}

const SelectedBtn = styled.Pressible<SelectedProps>`
  justify-content: center;
  align-items: center;
  
  color: ${({ isSelected }) => 
  	isSelected ? 'red' : 'black'
  }
`

const SelectedBtnPage = () => {
  const [isSelected, setIsSelected] = useState(false)
  const onPress = () => setIsSelected(!isSelected)
  
  return (
  	<SelectedBtn isSelected={isSelected} onPress={onPress}/>
  )
}

여러가지 css 속성을 변경할 경우 

1. react native styled component 모듈에서 {css} 를 import한다. 

2. css` `을 추가하고 백틱 안에 필요한 속성을 추가한다. 

//SelectedBtnPag.tsx

interface SelectedProps {
	isSelected: boolean
}

const SelectBtn = styled.Pressable<SelectedProps>`
${({isSelected}) => 
  isSelected ? css`
    background-color: 'black';
    border-width: 2px;
    border-style: solid;
    border-color: white;
  ` 
  : css`
  	background-color: 'yellow';
  `
}
`

const SelectedBtnPage = () => {
  const [isSelected, setIsSelected] = useState(false)
  const onPress = () => setIsSelected(!isSelected)
  
  return (
  	<SelectedBtn isSelected={isSelected} onPress={onPress}/>
  )
}

 

'CSS' 카테고리의 다른 글

21.12.31 UI 디자인 트렌드  (0) 2022.01.01
21.12.21 flex-속성  (0) 2021.12.21
21.12.13 text shadow  (0) 2021.12.13
21.01.15 프로젝트#1 Grid Garden  (0) 2021.01.16
21.01.13 프로젝트#1 햄버거 버튼  (0) 2021.01.14