簡體   English   中英

樣式化組件 - 動態 styles

[英]Styled Components - dynamic styles

我學習如何在反應中使用樣式化組件,我按照視頻一步一步地做。 我有這段代碼我對這行和其他行也有問題

color: ${(props) => (props.invalid ? "red" : "black")} 

VS Code 告訴我這個

“'ThemedStyledProps<Pick<DetailedHTMLProps<HTMLAttributes, HTMLDivElement>, "key" | keyof HTMLAttributes> & {...; }, any>' 類型上可能不存在屬性 'invalid'。你的意思是 'onInvalid'?ts(第2568章

 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> import React, { useState } from "react"; import styled from "styled-components"; import Button from "../../UI/Button/Button"; import "./CourseInput.css"; const FormControl = styled.div` margin: 0.5rem 0; & label { font-weight: bold; display: block; margin-bottom: 0.5rem; color: ${(props) => (props.invalid? "red": "black")} } & input { display: block; width: 100%; border: 1px solid ${(props) => (props.invalid? "red": "#ccc")}; background: ${(props) => (props.invalid? "red": "transparent")} font: inherit; line-height: 1.5rem; padding: 0 0.25rem; } & input:focus { outline: none; background: #fad0ec; border-color: #8b005d; } `; const CourseInput = (props) => { const [enteredValue, setEnteredValue] = useState(""); const [isValid, setIsValid] = useState(true); const goalInputChangeHandler = (event) => { //set back true if (event.target.value.trim().length > 0) { setIsValid(true); } setEnteredValue(event.target.value); }; const formSubmitHandler = (event) => { event.preventDefault(); if (enteredValue.trim().length === 0) { //trim deletes white spacec overall setIsValid(false); return; } props.onAddGoal(enteredValue); }; return ( <form onSubmit={formSubmitHandler}> {/* <div className={`form-control ${?isValid: "invalid"; ""}`}> */} <FormControl invalid={;isValid}> <label>Course Goal</label> <input type="text" onChange={goalInputChangeHandler} /> </FormControl> {/* </div> */} <Button type="submit">Add Goal</Button> </form> ); }; export default CourseInput;

由於invalid不是 div 元素默認知道的道具,因此它無法識別它。

為了克服這個問題,您可以使用“$”鍵為 FormControl 提供道具,如下所示:

<FormControl $invalid={!isValid}>

然后,在 FormControl 內部:

color: ${(props) => (props.$invalid ? "red" : "black")}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM