简体   繁体   English

反应-在TypeScript中将组件与子组件组成

[英]REACT - Composition of a component with subcomponents in TypeScript

react-bootstrap let you create a modal component with: react-bootstrap使您可以使用以下方式创建模式组件:

<Modal>
    <Modal.Header>
        <Modal.Title>Modal heading</Modal.Title>
    </Modal.Header>
    <Modal.Body>
        <h4>Text in a modal</h4>
    </Modal.Body>
    <Modal.Footer>
        <Button>Close</Button>
    </Modal.Footer>
</Modal>

I want to do a composition of the modal component and create a MyModal component: 我想组成模态组件并创建一个MyModal组件:

import * as React from 'react';
import { Modal, ModalBody, ModalProps } from 'react-bootstrap';

interface Props extends ModalProps {
  plain?: boolean;
}

class MyModal extends React.Component<Props> {

  static Body: typeof ModalBody;

  constructor(props: Props) {
    super(props);
  }

  render() {
    const { plain, ...other } = this.props;
    return (
      <Modal className={plain ? 'plain' : ''} {...other} />
    );
  }
}

export default MyModal;

but if I use it like this: 但是如果我这样使用它:

import MyModal from './MyModal';

...

render() {
  return (
    <MyModal plain={true}>
      <MyModal.Body>
        <p>Hello!</p>
      </MyModal.Body>
    </MyModal>
  );
}

I get the following error: 我收到以下错误:

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. 警告:React.createElement:类型无效-预期为字符串(对于内置组件)或类/函数(对于复合组件),但得到:未定义。 You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports. 您可能忘记了从定义文件中导出组件,或者可能混淆了默认导入和命名导入。

Any idea what's going wrong? 知道发生了什么事吗?

static Body: typeof ModalBody;

is undefined , so it cannot be used as <MyModal.Body> . undefined ,因此不能用作<MyModal.Body>

In case it's inherited from wrapped component, it should be: 如果它是从包装的组件继承的,则应为:

static Body = ModalBody;

Where Body type is inferred. 推断Body类型的地方。

This problem could be avoided by using TypeScript strict ( strictNullChecks ) compiler option. 通过使用TypeScript strictstrictNullChecks )编译器选项可以避免此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM