【问题标题】:Build a layout component in React and TypeScript在 React 和 TypeScript 中构建布局组件
【发布时间】:2021-01-30 16:45:28
【问题描述】:

我不知道如何解释,所以它是有道理的,所以我将使用 Razor (C#) 示例。在 Razor 中,我们可以定义布局页面,然后像这样声明我们想要渲染 body 的位置:

<html>
    <body>
        @RenderBody()
    </body>
</html>

假设我有一个用于布局的 React 组件:

class Layout extends React.Component<any, any> {
    constructor(props) {
        super(props);
    }

    public render() {
        return (
            <Container fluid>
                <Row className="row">
                    <Col className="col-sm">
                        <NavBar />
                        //How to achieve the same functionality as RenderBody() here?
                    </Col>
                </Row>
            </Container>
        );
    }
}

所以当我创建一个子组件时,我可以这样做:

public render(){
    return(
        <Layout>
            <div>I am some content!</div>
        </Layout>
    );
}

这可能吗?如果有,怎么做?

【问题讨论】:

    标签: reactjs typescript layout


    【解决方案1】:

    是的,您可以使用children 属性打印&lt;Layout&gt; 中的任何内容。因此,将您的 Layout 组件更改为如下内容:

    <Container fluid>
      <Row className="row">
        <Col className="col-sm">
          <NavBar />
                            
          {this.props.children}
        </Col>
      </Row>
    </Container>
    

    Here 是一个更详细解释它的答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-25
      • 2016-05-03
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 2020-10-25
      相关资源
      最近更新 更多