组件是React库的构建块。有两种类型的组件。
有状态的组件
无状态组件
有状态组件具有可以在内部操作的局部状态对象。
无状态组件没有本地状态对象,但是我们可以使用React钩子添加一些状态。
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语句使用此功能组件。
实际文件的路径可能需要根据相对位置进行更改。
import Player from './Player'
如果您已经注意到上面的import语句中没有提及文件扩展名。这是因为默认情况下,构建工作流会自动将其视为js或jsx文件类型。如果文件的类型不同,那么我们也需要提及文件的扩展名。
这个Player功能组件可以在jsx元素中使用-
<Player/>
该功能组件可以在任何地方多次使用。它的可重用组件。
我们有一个下面的播放器组件
import React from 'react'; const player = () => { return ( <p>I'm a Player</p> ); } export default 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后,请从项目目录在终端上启动。
要在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访问属性
我们在玩家David上拥有一个儿童财产,我们可以通过以下方式访问它-
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属性让我们访问该文本。