Propslarga qarab stylelar| Hooks qo'llanma 5
Komponentga berilgan propertylarga qarab turli stylelarni ko'rsatish.
Bu maqola style mavzusining davomi, props haqida esa alohida maqola yoziladi.
CodeSandbox link
Bu darsdagi to'liq kodni quyidan topa olasiz: https://codesandbox.io/s/styles-via-props-uy638r
Componentingizni yarating
Keling o'tgan maqolada yaratgan button componentimizni qayta ishlatamiz. Biz buttonni ikki marta takrorlaymiz va ikkisi orasidagi farqni bilishimiz mumkin.
import React from "react"; import styled from "styled-components"; const Buttons = () => { return ( <div> <Button>Sign in</Button> <Button>Sign in</Button> </div> ); }; export default Buttons; const Button = styled.button` background: linear-gradient(91.4deg, #2fb8ff 0%, #9eecd9 100%); padding: 12px 25px; border: none; border-radius: 30px; color: white; font-weight: bold; font-family: Segoe UI, sans-serif; `;
Props berish
Shartli stylelar qo'shish uchun buttonlardan biriga property beramiz. Bu property disabled bo'la qolsin va uni ikkinchi buttonga beramiz. Agar buttonda disabled propertysi bo'lsa, biz uning backgroundini kulrang rangga o'zgaradigan qilamiz.
const Buttons = () => { return ( <div> <Button>Sign in</Button> <Button disabled>Sign in</Button> </div> ); };
Pasdagi styled.button ning background ini quyidagi kodga almashtiramiz.
background: ${(props) => props.disabled ? "grey" : "linear-gradient(91.4deg, #2fb8ff 0%, #9eecd9 100%)"};
Bu Button komponentimizning disabled propertiysini bor yoki yo'qligiga qarab background uchun grey yoki lineardan birini tanlaydi.
Yakuniy code
import React from "react"; import styled from "styled-components"; const Buttons = () => { return ( <div> <Button>Sign in</Button> <Button disabled>Sign in</Button> </div> ); }; export default Buttons; const Button = styled.button` background: ${(props) => props.disabled ? "grey" : "linear-gradient(91.4deg, #2fb8ff 0%, #9eecd9 100%)"}; padding: 12px 25px; border: none; border-radius: 30px; color: white; font-weight: bold; font-family: Segoe UI, sans-serif; `;
Propslardan biz juda ko'p foydalanamiz. Siz componentingizga istalgan turdagi ma'lumotni props ko'rinishida berib yuborsangiz bo'ladi. Propslar haqida esa boshqa maqolada yana qayta gaplashamiz.