在 React.js 中创建函数式组件
让我们看看如何创建一个简单的 React 函数式组件
组件是 React 库的构建块。组件有两种类型。
- 有状态组件
- 无状态组件
有状态组件有一个本地状态对象,可以在内部进行操作。
无状态组件没有本地状态对象,但我们可以在其中使用 React hook 添加一些状态。
创建一个简单的 ES6 函数
const player = () => {
}这里我们使用 const 关键字作为函数名,以便它不会意外地被修改。让我们添加一个带有某些 jsx 代码的 return 语句。
const player = () => {
return (
<p>I'm a Player</p>
);
}要在 JavaScript 文件中使用 jsx,我们需要像下面这样导入 React
import React from 'react';
const player = () => {
return (
<p>I'm a Player</p>
);
}最后,我们需要导出此函数
export default player;
现在,我们可以使用下面的导入语句使用此函数式组件。
实际文件的路径可能需要根据相对位置进行更改。
import Player from './Player'
如果您注意到,上面的导入语句中没有提到文件扩展名。这是因为构建工作流默认情况下会自动将其视为 js 或 jsx 文件类型。如果文件类型不同,则也需要提及文件扩展名。
此 Player 函数式组件可以在 jsx 元素中使用,例如:
<Player/>
此函数式组件可以在任何地方使用,也可以多次使用。它是一个可重用的组件。
添加动态内容
我们有一个下面的 Player 组件
import React from 'react';
const player = () => {
return (
<p>I'm a Player</p>
);
}
export default player;Player 组件导入到 app.js 文件中
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Player from './Player'
function App() {
return (
<div className="App">
<Player/>
<Player/>
<Player/>
</div>
);
}
export default App;现在,假设我们想为每个玩家显示一些随机分数,我们可以这样做:
import React from 'react';
const player = () => {
return (
<p>I'm a Player: My score {Math.floor(Math.random() * 50)}</p>
);
}
export default player;保存文件后,从项目目录的终端运行 npm start。
要在 jsx 中添加动态内容,我们可以在 {} 花括号内执行此操作。
让我们看看如何向函数式组件添加属性或特性
import React from 'react';
import './App.css';
import Player from './Player'
function App() {
return (
<div className="App">
<Player name="Smith" score="100"/>
<Player name="David" score="99">Plays for Australia </Player>
<Player name="Phil" score="80"/>
</div>
);
}
export default App;我们可以像上面一样向 Player 元素添加属性。要访问为 Player 定义的函数式组件中的属性,我们需要像下面这样传递一个参数。
import React from 'react';
const player = (props) => {
return (
<p>I'm a Player: My name {props.name} and my score is {props.score}</p>
);
}
export default player;函数的参数名称可以不同,但标准是使用 props 作为其名称。我们使用 props.name 和**props.score 在 {} 花括号内**访问属性
访问 JSX 元素的子元素
我们在 David 的 player 上有一个 children 属性,我们可以像下面这样访问它:
import React from 'react';
const player = (props) => {
return (
<div>
<p>I'm a Player: My name {props.name} and my score is {props.score}</p>
{props.children}
</div>
);
}
export default player;{props.children} 属性使我们能够访问该文本。
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP