reactjs - 按钮在反应中使用功能组件不起作用
问题描述
我是 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,但它显示
你好按钮在这里
解决方案
这是工作代码:
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;
这就是您的代码有什么问题:
showAction
函数没有返回任何内容(因为您使用大括号而不是括号)。- 所有 jsx 元素都必须有一个父元素。请注意,我添加了一个
<div>
包装按钮和标题组件的组件。您也可以使用<span>
或您选择的任何其他组件/标签。
推荐阅读
- javascript - Bootstrap 4:当上面的部分关闭时关闭打开部分
- c++ - 按住键直到事件 C++
- python - 如何读取在记录的实际 JSON 字典部分之前具有整数值的数据文件?
- angular - chartjs-node-canvas 甜甜圈图
- ruby - 如何使用 Ruby-Vips 高效地创建纯色背景图像
- javascript - 如何通过 xpath 获取元素?
- amazon-web-services - 嘿,我如何才能看到为什么我的实时技能中的用户会出现后备意图?
- html - 如何使用 MathJax 在 Materialise 的工具提示中显示 Latex 公式?
- python - 自动播放 matplotlib FuncAnimation jsthml 元素
- mysql - 如何在mysql中为时间戳列设置默认值