【问题标题】:Styled Components - dynamic stylesStyled Components - 动态样式
【发布时间】:2022-01-21 21:15:39
【问题描述】:

我学习如何在 React 中使用样式化组件,我会按照视频逐步进行操作。我有这段代码我对这行和其他行也有问题

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

VS Code 告诉我这个

“类型上可能不存在属性‘无效’ 'ThemedStyledProps, "键" | HTML属性的关键> & { ...; },任何>'。你是说'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;

【问题讨论】:

    标签: javascript reactjs dynamic properties styled-components


    【解决方案1】:

    由于 invalid 不是 div 元素知道的 prop,默认情况下它不会识别它。

    要克服这个问题,您可以使用“$”键为 FormControl 提供道具,如下所示:

    <FormControl $invalid={!isValid}>
    

    然后,在 FormControl 内部:

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

    【讨论】:

      猜你喜欢
      • 2018-10-20
      • 2021-11-04
      • 2021-04-06
      • 2021-08-26
      • 2023-03-26
      • 2020-08-31
      • 2018-01-18
      • 2018-09-06
      • 2021-11-01
      相关资源
      最近更新 更多