試圖做出一些不同的東西,但也許根本不一樣。
創建一個視圖,其中有不同的組件,其中還有用于頁面部分的組件,并且在這些組件中還有其他幾個較小的組件(如按鈕等)。當我有組件樣式的組件時,我在 Chrome 控制臺中遇到錯誤
Section(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
它的外觀:
import { Component, ReactNode } from "react";
import Section from "../../../components/Section/Section";
import Button from "../../../components/Button/Button";
class About extends Component{
render(): ReactNode {
return (
<Section theme="dark" title="About">
About content
<div className="about-content">
<p>Lorem ipsum dolor sit amet...</p>
<Button theme="primary">Contact us</Button>
</div>
</Section>
);
}
}
export default About;
當我禁用<Button>一切作業正常
和<Section>組件:
import React from "react";
import "./themes.scss";
interface SecProps {
title?: string;
smalltext?: string;
theme?: string; // dark, light, purple, gray
}
class Section extends React.Component<SecProps>{
constructor(props: any) {
super(props);
this.state = {
title: "",
smalltext: "",
theme: ""
};
}
private sectionTheme(): string | undefined {
switch (this.props.theme) {
case "dark":
return "black";
case "light":
return "lightgray";
case "purple":
case "gray":
return this.props.theme;
default:
return "";
}
}
public render() {
return(
<section className={this.sectionTheme()}>
<div className="container">
<div className="sect-head">
{(this.props.title) ? <h2>{this.props.title}</h2> : ""}
{(this.props.smalltext) ? <small>{this.props.smalltext}</small> : ""}
</div>
<div className="sect-content">
{this.props.children}
</div>
</div>
</section>
);
}
}
export default Section;
還有<Button>組件:
import React from "react";
interface BtnProps{
type?: string; // button, link
theme?: string; // primary, outline
url?: string;
onClick?: React.MouseEventHandler<HTMLButtonElement>;
}
class Section extends React.Component<BtnProps>{
constructor(props: any){
super(props);
this.state = {
type: "button",
theme: "",
url: "#"
};
}
render() {
const btn = this.props;
if(btn.type === "button"){
return(
<button
className={this.buttonClass()}
onClick={this.props.onClick}
>
{btn.children}
</button>
)
}else if(btn.type === "link"){
return(
<a
href={btn.url}
className={this.buttonClass()}
>
{btn.children}
</a>
)
}
}
private buttonClass() : string | undefined {
switch(this.props.theme){
case "primary":
return "primary";
case "outline":
return "outline";
default:
return "";
}
}
}
export default Section;
是的,我是 React 的新手,從某事開始,找不到任何正確的答案
uj5u.com熱心網友回復:
問題很清楚:Button當條件不匹配時,組件不會回傳任何內容。
您只需要return null在 render 方法的末尾添加一個簡單的Button:
render() {
const btn = this.props;
...
return null;
}
另一種選擇是在使用時添加缺少的道具之一Button:
<Button theme="primary" type="button">Contact us</Button>
或者
<Button theme="primary" type="link">Contact us</Button>
無論哪種情況,我都建議您保留方法的return null內部render。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/412517.html
標籤:
上一篇:背景關系和減速器不回傳狀態
