在 React 和 TypeScript 中构建布局组件
Build a layout component in React and TypeScript
我不知道如何解释这个,所以它是有道理的,所以我将使用 Razor (C#) 示例。在 Razor 中,我们可以定义布局页面,然后像这样声明我们想要渲染主体的位置:
<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>
);
}
这可能吗?如果是,怎么做?
是的,您可以使用 children
属性来打印 <Layout>
中的任何内容。因此,将 Layout
组件更改为如下内容:
<Container fluid>
<Row className="row">
<Col className="col-sm">
<NavBar />
{this.props.children}
</Col>
</Row>
</Container>
是一个更详细解释它的答案。
我不知道如何解释这个,所以它是有道理的,所以我将使用 Razor (C#) 示例。在 Razor 中,我们可以定义布局页面,然后像这样声明我们想要渲染主体的位置:
<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>
);
}
这可能吗?如果是,怎么做?
是的,您可以使用 children
属性来打印 <Layout>
中的任何内容。因此,将 Layout
组件更改为如下内容:
<Container fluid>
<Row className="row">
<Col className="col-sm">
<NavBar />
{this.props.children}
</Col>
</Row>
</Container>