[英]How to render different element based on props?
我在一個項目中使用了非常不同的標題。
這是當前的外觀(進行中)
import * as React from 'react';
import './Heading.css';
import { MarkupContent } from 'app-types';
import HeadingElement from './HeadingElement';
interface HeadingProps {
type: 'fullwidth' | 'emphasis';
children: MarkupContent;
element: 'h1' | 'h2';
}
function Heading(props: HeadingProps) {
switch (props.type) {
case 'fullwidth':
return (
<div className="big-heading-container">
<div className="big-heading-section">
<HeadingElement element={props.element} classes="big-heading-text">
{props.children}
</HeadingElement>
</div>
</div>
);
case 'emphasis':
return (
<h2 className="heading--emphasized">
{props.children}
</h2>
);
default:
return (
<></>
);
}
}
export default Heading;
import * as React from 'react';
import { MarkupContent } from 'app-types';
interface HeadingElementProps {
element: 'h1' | 'h2';
classes: string;
children: MarkupContent;
}
function HeadingElement(props: HeadingElementProps) {
switch (props.element) {
case 'h1':
return (
<h1 className={props.classes}>{props.children}</h1>
);
case 'h2':
return (
<h2 className={props.classes}>{props.children}</h2>
);
default:
return (
<></>
);
}
}
export default HeadingElement;
@import "../../parameters.scss";
.big-heading {
&-container {
padding: 90px 25px 0 25px;
background-image: url("../../images/heading-background.png");
border-bottom: 1px solid $green;
}
&-section {
max-width: $max-width;
margin: 0 auto 0 auto;
display: flex;
}
&-text {
font-size: 1.5rem;
text-transform: uppercase;
border-bottom: 4px solid $green;
padding: 0 0 15px 0;
display: inline;
}
}
.heading--emphasized {
font-size: 1.7rem;
line-height: 2.0rem;
font-weight: bold;
text-transform: uppercase;
display: inline;
border-top: solid 4px #94d500;
padding-top: 10px;
padding-right: 30px;
}
我對switch語句特別感興趣,在該語句中,我返回傳遞了props.children
的or元素。
這是一個好方法還是有更好的方法來切換基於道具渲染的元素?
在我看來很好。 相同的方法還用於更改狀態以呈現不同的內容。
如果props.element
只能是“ h1”或“ h2”(兩個可能的值),我寧願使用三進制條件語句,而不是switch語句。 這樣的東西看起來更好嗎?
function HeadingElement(props: HeadingElementProps) {
return props.element === 'h1' ? <h1 className={props.classes}>{props.children}</h1> : <h2 className={props.classes}>{props.children}</h2>
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.