【问题标题】:How to NOT render/ hide a React component when no prop is passed?没有传递任何道具时如何不渲染/隐藏 React 组件?
【发布时间】:2022-01-03 18:47:59
【问题描述】:

TLDR:无法弄清楚为什么在没有传递任何 props 时组件仍在渲染。

所以我一直在构建一个 NextJS 应用程序,并且我有这个横幅组件,它显示在我网站的每个页面上。它有一些标题文本、按钮和图像:

const Banner = (props) => {
  return (
    <div className={bannerStyles.wrapper}>
      <div className={classnames(bannerStyles.banner, "wrap", "center")}>
        <div className={bannerStyles.banner_left}>
          <h1>{props.header}</h1>
          <div className={bannerStyles.button_wrapper}>
            <div className={bannerStyles.button}>
              <Button>{props.button || null}</Button>
            </div>
            <div className={bannerStyles.button}>
              <Button>{props.scnd_button || null}</Button>
            </div>
          </div>
        </div>
        <div className={bannerStyles.banner_right}>
          <Image src={props.image} alt=""></Image>
        </div>
      </div>
    </div>
  );
};

在这里面,你可以看到我有两个 Button 组件(MDEast 的东西是一个箭头图标):

const Button = ({children}) => {
    return (
            <div className={buttonStyles.button}>
                <Link href="/"><a>{children} <MdEast /></a></Link>
            </div>
    )
}

现在我想要一个选项,如果没有传递任何道具,按钮组件不会渲染/从页面中隐藏,因此它是每页可选的。然而,即使我没有在关于页面上传递任何道具,按钮仍然会呈现。 My about page:

const About = () => {
    return (
        <>
            <Banner 
                header="Hello this is my code"
                image={banner_placeholder}
            />
        </>
    )
}

PS。我对 React 和 NextJS 还很陌生,所以这可能是初学者的错误,或者我对基础知识的理解不够好,但是请有人指出我正确的方向吗?

【问题讨论】:

    标签: reactjs next.js components react-props


    【解决方案1】:

    有条件地渲染你可以使用的按钮:

    props.button &amp;&amp; &lt;Button&gt;{props.button}&lt;/Button&gt;

    当 props.button 为 falsy 时,按钮不会被渲染。

    【讨论】:

      猜你喜欢
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      • 2021-09-08
      • 2018-01-11
      相关资源
      最近更新 更多