代码之家  ›  专栏  ›  技术社区  ›  C Bauer

反应类型的子语法

  •  0
  • C Bauer  · 技术社区  · 6 年前

    我试图理解如何用非常具体的子类型构建一个反应组件,我想使用的语法是:

    <Stepper>
        <Stepper.Step>
            Some text/react element child
        </Stepper.Step>
        <Stepper.Step>
            Some other text/element
        </Stepper.Step>
    </Stepper>
    

    所以我把这段代码作为一个起点,但它会抛出一个错误,即使在我不从这里输出任何东西的情况下。props: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports. .

    class Step extends Component {
        constructor(props: any) {
            super(props);
            this.state = {
    
            };
        }
        render() {
            return (
                <li>{this.props.children}</li>
            );
        }
    }
    class Stepper extends Component {
        static Step: typeof Step;
        constructor(props: any) {
            super(props);
    
            this.state = {
    
            };
        }
        render() {
            return (
                <ul className="stepper">
                    {this.props.children}
                </ul>
            );
        }
    }
    

    请注意,我知道有些库中提供了这个功能,但我不想在我正在研究的核心代码库中添加任何新的库。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Andrew    6 年前

    您当前拥有的是一个什么类型的声明 Step 是。你没有真正定义价值

    static Step: typeof Step;
    

    应该是这个。我很确定类型将由typescript推断

    static Step = Step
    
        2
  •  2
  •   Elder    6 年前

    如果从步进器内部定义复合组件时移除类型of,并实际执行如下操作:

      static Step = Step;
    

    它应该能工作。您的问题是,type of将返回组件的类型(obj),而不是实际的组件。我在这里复制了您的代码,并用该更改进行了尝试,结果成功了:

    https://codesandbox.io/s/vigilant-thompson-mj1re