为什么不渲染子组件?

时间:2020-04-17 09:07:04

标签: javascript html reactjs react-native jsx

我已经在 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;

但是输出显示如下:

parastoo

出什么问题了?子<h1>为什么不渲染?

3 个答案:

答案 0 :(得分:1)

子组件是通过 children 道具传递给该组件的,即使只有一个子组件也是如此:

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

答案 1 :(得分:0)

它称为props.children。阅读文档章节Containment

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

我希望这会有所帮助!

答案 2 :(得分:0)

在React中,您可以将prop或属性传递给子组件。假设您有一个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>
  );
};

日历是父组件,您可以通过编写

传递日历属性
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>
    );
  }
};