如何在 JSX 中添加函数?
React.js使用JavaScript的 JSX 扩展来为我们编写应用程序提供更简单的方法。函数是任何 Web 应用程序中最重要的部分之一,使用它们,我们可以执行优化的计算和 UI 渲染,最终为我们提供一个完整构建的网站。在本文中,我们将讨论如何在 JSX 中添加函数。
创建 React 应用程序并安装模块:
第 1 步:使用以下命令创建一个 React 应用程序:
npx create-react-app foldername
第 2 步:创建项目文件夹(即文件夹名称)后,使用以下命令移动到该文件夹:
cd foldername
第 3 步:在您的系统上设置 React 环境后,我们可以从创建App.js文件开始,并以组件名称创建一个目录,我们将在其中编写所需的函数。
项目结构:它将如下所示。
现在让我们看看如何使用 JSX 添加函数。
示例 1:在此示例中,我们将考虑一个示例来演示如何将函数添加到我们的应用程序中。现在在组件的目录中,我们将创建一个display.js文件,该文件将包含要添加到应用程序中的显示函数。
display.js
import React from "react";
// This is the function that will be added to the application
function Display() {
return GeeksForGeeks
;
}
export default Display;
App.js
import "./styles.css";
// Importing the function
import Display from "./components/display";
export default function App() {
return (
{/* Creating custom JSX tag to return the function */}
);
}
display.js
import React from "react";
// The contents of the header can
// be modified in this function
function Display(props) {
return {props.name}
;
}
export default Display;
App.js
import "./styles.css";
// Importing the function
import Display from "./components/display.js";
export default function App() {
return (
{/*Customised JSX tag with different inputs*/}
);
}
现在,最后一步是将我们的函数合并到应用程序中。这可以通过将函数导入 App.js 文件并使用函数名称作为自定义 JSX 标记来完成。
应用程序.js
import "./styles.css";
// Importing the function
import Display from "./components/display";
export default function App() {
return (
{/* Creating custom JSX tag to return the function */}
);
}
输出:因此,我们可以看到在 JSX 代码中添加函数非常简单。提供的示例非常简单但复杂的渲染和所需的计算也可以在函数内部完成,然后可以在我们的应用程序代码中使用。
示例 2:现在在此示例中,我们将创建带有更改的display.js文件。这次我们将能够从App.js文件中更改标头的内容。
显示.js
import React from "react";
// The contents of the header can
// be modified in this function
function Display(props) {
return {props.name}
;
}
export default Display;
现在, 我们现在将在 App.js 文件中合并该函数,就像我们在前面的示例中所做的那样。
应用程序.js
import "./styles.css";
// Importing the function
import Display from "./components/display.js";
export default function App() {
return (
{/*Customised JSX tag with different inputs*/}
);
}
从代码中,我们现在可以预测输出。请注意,您只需更改标签中的name属性即可呈现自定义输出。
输出:
参考:
https://www.geeksforgeeks.org/reactjs-functional-components/
https://reactjs.org/docs/faq-functions.html