[英]Button does not work using function component in react
I am new to React and I've been told its a better way to use function components than class components and I have come to an error where I am unable to show components that I included, I don't really understand what is wrong hence the explanation might be wrong.我是 React 新手,有人告诉我使用 function 组件比使用 class 组件更好的方法,我遇到了一个错误,我无法显示我包含的组件,我真的不明白出了什么问题解释可能是错误的。
Please see my sandbox link for errors请查看我的沙盒链接以了解错误
https://codesandbox.io/s/sweet-andras-y1g6o?file=/src/App.jshttps://codesandbox.io/s/sweet-andras-y1g6o?file=/src/App.js
My code as below我的代码如下
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;
I am expecting it to show Hello {Button} Here Button is here, but instead it shows我期待它显示 Hello {Button} Here Button is here,但它显示
Hello Button is here你好按钮在这里
Here's the working code:这是工作代码:
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;
And here's what was wrong with your code:这就是您的代码有什么问题:
showAction
function wasn't returning anything (because you used braces instead of parentheses). showAction
function 没有返回任何内容(因为您使用大括号而不是括号)。<div>
that wraps the button and the heading component.<div>
。 You could have also used <span>
or any other component/tag of your choice.<span>
或您选择的任何其他组件/标签。@Jalaj has already broken down the problem very nicely, so the only thing I would like to add is that in the case of your showAction
element, you can skip adding parentheses or curly braces altogether. @Jalaj 已经很好地解决了这个问题,所以我唯一想补充的是,对于你的
showAction
元素,你可以完全跳过添加括号或花括号。 When doing so, JS assumes a return statement.这样做时,JS 假定一个 return 语句。 This will work like a charm:
这将像一个魅力:
const showAction = () =>
<Fragment>
<Button type="primary" size="small">
{" "}
{"View"}
</Button>
<h1>Here</h1>
</Fragment>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.