具有嵌套组件属性

时间:2018-02-16 09:08:21

标签: reactjs typescript

我想使用这样的组件:

<Grid>
 <Grid.Column>
  {/*some content*/}
 </Grid.Column>
</Grid>

Grid.tsx

export interface GridProps extends React.HTMLAttributes<HTMLDivElement> {
}

const Grid: React.SFC<GridProps> =({ children, ...props }) =>
        <div {...props}>
            {children}
        </div>

export interface GridColumnProps extends React.HTMLAttributes<HTMLDivElement> {
    size: 1 | 2 | 3 | 4,
    centered?: false
}

const Column: React.SFC<GridColumnProps> = ({ children, ...props }) =>
    <div {...props}>
        {children}
    </div>

Grid.Column = Column; 

在最后一行我有一个错误&#34;列不存在于StatelessComponent类型| GridProps |

1 个答案:

答案 0 :(得分:1)

您需要为Grid定义React.SFC<GridColumnProps>并且具有名为Column

的属性的自定义类型
type GridType = React.SFC<GridProps> & { Column: React.SFC<GridColumnProps> } 
const Grid: GridType =(({ children, ...props }) =>
        <div {...props}>
            {children}
        </div>) as GridType // Use a type assertion as our function does not have the Column Property yet

Grid.Column = Column;