【问题标题】:Component typing react typescript组件打字反应打字稿
【发布时间】:2020-04-14 19:04:16
【问题描述】:

场景:

我创建了 Text 组件;另一个 Tag 组件嵌入其中。

问题:

如何输入才能使其正常工作?现在出现一个错误,它不接受所需的样式。

错误是这样的:

Type '{ children: ReactNode; classNames: any; }' is not assignable to type 'IntrinsicAttributes'. Property 'children' does not exist on type 'IntrinsicAttributes'.ts(2322)

这是我的代码:

import React, { ReactNode } from 'react';
import styles from './Text.module.css';
import classNames from 'classnames/bind';

const cx = classNames.bind(styles);

interface ITextProps {
    variant: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'p1' | 'p2' | 'p3';
    bold?: boolean;
}

const tags = {
    h1: 'h1',
    h2: 'h2',
    h3: 'h3',
    h4: 'h4',
    h5: 'h5',
    h6: 'h6',
    p1: 'p',
    p2: 'p',
    p3: 'p',
};

const Text: React.FC<ITextProps> = ({ children, variant, bold }) => {
    const Tag = tags[variant];

    return <Tag classNames={cx({ title: variant === 'h1' })}>{children}</Tag>;
};

export default Text;

【问题讨论】:

标签: reactjs typescript


【解决方案1】:

使用React.createElement

创建并返回给定类型的新 React 元素。类型参数可以是
- 标签名称字符串(如'div''span'),
- React 组件类型(类或函数),
- 或 React 片段类型。

const Template = React.createElement(tags[variant], {}, children);

const App = () => {
  const tags = {
    h1: "h1",
    h2: "h2",
    h3: "h3",
    h4: "h4",
    h5: "h5",
    h6: "h6",
    p1: "p",
    p2: "p",
    p3: "p"
  };
  const Template = React.createElement(tags['h1'], {}, 'Text');
  return (
    <div className="App">
      {Template}
    </div>
  );
}
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

【讨论】:

  • 我做到了: const Text: React.FC = ({ children, variant, bold }) => { const Tag = React.createElement(tags[variant], {}, children );返回 {Tag}; };
  • 但我不明白是否要根据使用库 classNames/bind 的父元素中的道具使用不同的类
  • 示例:classNames={cx({ title: variant === 'h1', description: variant === 'p1' })}
  • @MaxAkinshin 传递给第二个参数,它接收道具
【解决方案2】:

您需要为您的界面添加子项类型声明以消除此错误。孩子的正确类型是 React.ReactNode - 尝试将您的界面修改为此...

interface ITextProps {
 children: React.ReactNode
 variant: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'p1' | 'p2' | 'p3';
 bold?: boolean;
}

【讨论】:

    猜你喜欢
    • 2019-07-11
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    • 2017-02-20
    • 2017-01-22
    • 2017-06-24
    相关资源
    最近更新 更多