React组件中的动态流类型

问题描述 投票:0回答:1

[请帮助我解决以下情况。我有React组件(称为Test),它使用仅在一个字段中不同的属性(该字段对什么组件没有影响)。但是当我使用此组件时,流程会抱怨该属性,而且我不知道如何正确解决它。如果您有解决此类问题的经验,请给我帮助。预先感谢!

import React, {Component} from 'react';

const Obj1 = {a: 'a', b: 'b'};
const Obj2 = {c: 'c', d: 'd'};

type TypesForA = $Values<typeof Obj1>;
type TypesForB = $Values<typeof Obj2>;

type A = Array<{|
  a: number,
  b: TypesForA,
|}>

type B = Array<{|
  a: number,
  b: TypesForB,
|}>

type Props = {prop: A | B};
type State = {prop: A | B};

export class Test extends Component<Props, State> {
   state = {prop: this.props.prop}
   render() {return null}

}

class Wrapper1 extends Component {     
   render() {
       return <Test prop={[{a: 1, b: Obj1}]}/> 
   }       
}


class Wrapper2 extends Component {     
   render() {
       return <Test prop={[{a: 1, b: Obj2}]}/> 
   }       
}

流量错误:enter image description here

reactjs flowtype
1个回答
0
投票

Here is a working example,但可能无法满足您的所有需求。主要问题似乎是Flow无法确定prop数组中元素的类型,但是显式键入该值是可行的,例如

class Wrapper1 extends Component<*> {     
   render() {
     const prop : A = [{a: 1, b: Obj1}];
     return <Test prop={prop}/> 
   }       
}
© www.soinside.com 2019 - 2024. All rights reserved.