在 React 中,您可以创建所谓的有状态和无状态功能组件。无状态组件是简单的可重用组件,不需要维护状态。这是一个简短的演示 ( http://codepen.io/PiotrBerebecki/pen/yaoOKv ) 向您展示了如何创建它们以及它们如何访问从父级(有状态组件)传递的props。
一个简单的例子可能是App
Facebook.com 上的理论状态组件。它可以维护状态以跟踪用户是登录还是注销。然后在它的render()
方法中,它将显示一个LoginLogout
传递给它当前状态的无状态按钮组件。然后LoginLogout
无状态组件将显示:
- 如果用户未登录,则为“登录”文本,或
- 如果用户已登录,则为“注销”文本。
您可以在此处了解有关有状态与无状态组件的更多信息:有状态和无状态之间的 ReactJS 区别以及此处React.createClass 与 ES6 箭头函数
// Stateful component
class FacelookApp extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoggedIn: false
};
}
receiveClick() {
this.setState({
isLoggedIn: !this.state.isLoggedIn
});
}
render() {
return (
<div>
<h4>Welcome, I'm a stateful parent called Facelook App</h4>
<p>I maintain state to monitor if my awesome user logged
in. Are you logged in?<br />
<b>{String(this.state.isLoggedIn)}</b>
</p><br />
<p>Hi, we are three stateless (dumb) LoginLogout buttons
generated using different ES6 syntax but having the same
functionality. We don't maintain state. We will tell
our parent if the user clicks on us. What we render is
decided by the value of the prop sent to us by our parent.
</p>
<LoginLogout1 handleClick={this.receiveClick.bind(this)}
isLoggedIn={this.state.isLoggedIn}/>
<LoginLogout2 handleClick={this.receiveClick.bind(this)}
isLoggedIn={this.state.isLoggedIn}/>
<LoginLogout3 handleClick={this.receiveClick.bind(this)}
isLoggedIn={this.state.isLoggedIn}/>
</div>
);
}
}
// Stateless functional components
// created in 3 equally valid ways
const LoginLogout1 = (props) => {
return (
<div>
<button onClick={() => props.handleClick()}>
LoginLogout v1 --- {props.isLoggedIn ? 'Log Out' : 'Log In'}
</button>
</div>
);
};
// or
const LoginLogout2 = ({handleClick, isLoggedIn}) => (
<div>
<button onClick={() => handleClick()}>
LoginLogout v2 --- {isLoggedIn ? 'Log Out' : 'Log In'}
</button>
</div>
);
// or
const LoginLogout3 = ({handleClick, isLoggedIn}) => {
return (
<div>
<button onClick={() => handleClick()}>
LoginLogout v3 --- {isLoggedIn ? 'Log Out' : 'Log In'}
</button>
</div>
);
};
ReactDOM.render(
<FacelookApp />,
document.getElementById('app')
);