【问题标题】:Type '{ flag: boolean; }' is not assignable to type 'IntrinsicAttributes & boolean'输入 \'{ 标志:布尔值; }\' 不可分配给类型 \'IntrinsicAttributes & boolean\'
【发布时间】:2022-11-16 21:01:34
【问题描述】:

我从 TypeScript 开始,在将元素传递给另一个组件时出现错误,我不知道该怎么做。

Cards 组件错误

export default function MyProject() {
  const [flag, setFlag] = useState(false)
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {

        if (entry.isIntersecting) {
          setTimeout(() => {setFlag(true)}, 300)
        }
      },
      {
        root: null,
        rootMargin: "0px",
        threshold: 0.1
      }
    );
    if (ref.current) {
      observer.observe(ref.current);
    }
  }, [ref]);

    return ( 
        <>
        <div className="project" id='projects'>
            <div className="project__cards"
            ref={ref} 
                     style={{opacity: flag ? 1 : 0}}>
              <Cards flag={flag}/>
            </div>
        </div>
        </>
     );
}

我一直在寻找附录,但我认为我无法很好地搜索;//

【问题讨论】:

  • 你能展示Cards组件吗?

标签: reactjs typescript


【解决方案1】:

我能够通过像这样定义 Cards 组件来重现您的错误:

// produces error
export default function WrongCards(flag: boolean) {
/* ... */
}

但是您需要按照以下方式定义道具:

// produces no error
export default function WorkingCards(props: { flag: boolean }) {
/* ... */
}

您可以在这个sandbox 中查看整个实现。

【讨论】:

    猜你喜欢
    • 2023-01-18
    • 2020-01-06
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 2021-12-03
    相关资源
    最近更新 更多