首页 文章资讯内容详情

React.js无状态与有状态

2026-06-04 1 花语

了解无状态和有状态反应组件之间的差异

在状态管理中,我们了解了如何在发生更改时处理状态以做出反应。

无状态组件是简单的功能组件,没有局部状态,但请记住,在功能组件中添加状态行为也有反应。

有状态组件可以包含状态对象和事件处理功能,以及用户操作。

无状态组件本质上是纯净的,它执行非常特定的任务。

import React from react; const player = (props) => { return ( <div> <p>Im a Player: My name {props.name} and my score is {props.score}</p> {props.children} </div> ); } export default player;

上面是一个这样的功能组件,它仅显示从另一个组件传递的props属性。我们可以从位于类组件(容器)中的功能组件调用事件处理函数。

容器意味着包含一些本地状态或事件或用户操作。

我们可以在功能组件中添加一些逻辑动态代码,但不能修改状态或应用程序数据。

功能组件的通过方法引用

在动态输出文章中,我们已经看到了如何将属性从父组件传递到子功能组件。与此类似,我们可以添加一个方法引用。

import React, {Component} from react; import ./App.css; import Player from ./Player class App extends Component { state = { players:[ {name: Smith, score:100 }, {name: David, score:90}, {name: Phil, score:80} ], otherObject:Test } switchPlayerHandler = () =>{ this.setState({players:[ {name: Smith, score:200}, {name: David, score:290}, {name: Phil, score:380}]}); } render(){ return ( <div className="App"> <button onClick={this.switchPlayerHandler}> Switch Player </button> <Player name={this.state.players[0].name} score={this.state.players[0].score} click={this.switchPlayerHandler}/> <Player name={this.state.players[1].name} score={this.state.players[1].score} click={this.switchPlayerHandler}> Plays for Australia </Player> <Player name={this.state.players[2].name} score={this.state.players[2].score} click={this.switchPlayerHandler}/> </div> ); } } export default App;

观察我们传递了一个方法ref

<Player name={this.state.players[2].name} score={this.state.players[2].score} click={this.switchPlayerHandler}/>

我们可以在类似于onClick函数调用的功能组件上使用它

import React from react; const player = (props) => { return ( <div> <p onClick={props.click}>Im a Player: My name {props.name} and my score is {props.score} </p> {props.children} </div> ); } export default player;

对功能部件中的方法引用进行参数

<button onClick={this.switchPlayerHandler.bind(this,John,Test)}> Switch Player </button>

使用上述语法,我们可以将其作为类绑定的第一个参数传递,而其余参数则是我们要传递的值。

switchPlayerHandler = (newName,secondName) =>{ this.setState({players:[ {name: newName, score:200}, {name: secondName, score:290}, {name: Phil, score:380} ]}); }

传递的值可以在上面所示的函数中使用。

还有另一种方法可以传递方法参数。

onClick={ () => this.switchPlayerHandler(Michel,Stark) }

上面是一个匿名函数调用。它的工作原理相同。与第一种方法相比,该方法效率不高,因为React使用第二个匿名函数调用进行了一些渲染。这取决于我们是否不考虑性能下降。

状态或应用程序数据修改应在几个选定的组件中进行以避免复杂性。