【问题标题】:Why isn't the component child rendered?为什么不渲染组件子项?
【发布时间】:2020-04-17 09:07:04
【问题描述】:

我在APP.js组件中写了如下代码:

import React from "react";
import Exam from "./exam.js";

export default function App() {
   return (
      <Exam>
        <h1>hashemi</h1>
      </Exam>
   );
}

我在 exam.js 组件中编写了以下代码:

import React from "react";

const Exam = ({child}) => {
  return (
    <div>
      <p>parastoo</p>
      {child}
    </div>
  );
};
export default Exam;

但输出显示如下:

跳伞

有什么问题?为什么子&lt;h1&gt; 不渲染?

【问题讨论】:

    标签: javascript html reactjs react-native jsx


    【解决方案1】:

    子组件通过 children 属性传递给组件,即使只有一个子组件:

    const Exam = ({children}) => {
      return (
        <div>
          <p>parastoo</p>
          {children}
        </div>
      );
    };
    

    【讨论】:

      【解决方案2】:

      它叫做props.children。阅读文档部分Containment

      const Exam = (props) => {
        return (
          <div>
            <p>parastoo</p>
            {props.children}
          </div>
        );
      };
      

      我希望这会有所帮助!

      【讨论】:

        【解决方案3】:

        在 React 中,您可以将 props 或属性传递给子组件。假设您有一个 App 组件,它呈现一个名为 CurrentDate 的子组件,它是一个无状态功能组件。您可以通过以下方式将 CurrentDate 传递给日期属性:

        const CurrentDate = (props) => {
          return (
            <div>
              { /* change code below this line */ }
              <p>The current date is: {props.date} </p>
              { /* change code above this line */ }
            </div>
          );
        };
        

        Calender 是一个父 Component,可以通过写法给 Calender 传递一个日期属性

        class Calendar extends React.Component {
          constructor(props) {
            super(props);
          }
          render() {
            return (
              <div>
                <h3>What date is it?</h3>
                { /* change code below this line */ }
                <CurrentDate date={Date()}/>
                { /* change code above this line */ }
              </div>
            );
          }
        };
        

        【讨论】:

          猜你喜欢
          • 2018-01-09
          • 1970-01-01
          • 2017-07-12
          • 2021-01-24
          • 2021-05-28
          • 1970-01-01
          • 1970-01-01
          • 2011-03-01
          • 2019-12-27
          相关资源
          最近更新 更多