首页 > 解决方案 > 按钮在反应中使用功能组件不起作用

问题描述

我是 React 的新手,我被告知它是一种比类组件更好的使用函数组件的方法,我遇到了一个错误,我无法显示我包含的组件,我真的不明白出了什么问题解释可能是错误的。

请查看我的沙盒链接以了解错误

https://codesandbox.io/s/sweet-andras-y1g6o?file=/src/App.js

我的代码如下

import React from "react";
import { Button } from "antd";

const Order = () => {
  const showAction = () => {
    <Button type="primary" size="small">
      {" "}
      {"View"}
    </Button>;
    <h1>Here</h1>;
  };
  return (
    <div>
      <h1>Hello{showAction()} Button is here</h1>
    </div>
  );
};

export default Order;

我期待它显示 Hello {Button} Here Button is here,但它显示

你好按钮在这里

标签: reactjs

解决方案


这是工作代码:

import React from "react";
import { Button } from "antd";

const Order = () => {
  const showAction = () => (
    <div>
      <Button type="primary" size="small">
        {" "}
        {"View"}
      </Button>
      <h1>Here</h1>
    </div>
  );
  return (
    <div>
      <h1>Hello{showAction()} Button is here</h1>
    </div>
  );
};

export default Order;

这就是您的代码有什么问题:

  1. showAction函数没有返回任何内容(因为您使用大括号而不是括号)。
  2. 所有 jsx 元素都必须有一个父元素。请注意,我添加了一个<div>包装按钮和标题组件的组件。您也可以使用<span>或您选择的任何其他组件/标签。

推荐阅读