组件打字反应打字稿

时间:2020-04-14 10:52:18

标签: reactjs typescript

场景:

我创建了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;

2 个答案:

答案 0 :(得分:0)

使用React.createElement

创建并返回给定类型的新React元素。类型参数可以是
-标签名称字符串(例如 @EnableHazelcastHttpSession @Configuration public class HazelcastHttpSessionConfig { @Bean public HazelcastInstance hazelcastInstance() { Config config = new Config(); MapAttributeConfig attributeConfig = new MapAttributeConfig() .setName(HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE) .setExtractor(PrincipalNameExtractor.class.getName()); config.getMapConfig(HazelcastIndexedSessionRepository.DEFAULT_SESSION_MAP_NAME) .addMapAttributeConfig(attributeConfig).addMapIndexConfig( new MapIndexConfig(HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE, false)); return Hazelcast.newHazelcastInstance(config); } @Bean public Config config() { Config config = new Config(); JoinConfig joinConfig = config.getNetworkConfig().getJoin(); joinConfig.getMulticastConfig().setEnabled(false); joinConfig.getTcpIpConfig().setEnabled(true).setMembers(singletonList("127.0.0.1")); return config; } @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/haz").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } 'div'),
-React组件类型(类或函数),
-或React片段类型。

'span'

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"));

答案 1 :(得分:0)

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

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