我正在关注一个React教程,这是作者提供的用于创建基本React组件的示例代码:
const React = require('react') const ReactDOM = require('react-dom') const App = () => { return ( <div className='app-container'> <h1>Hello</h1> </div> ) } ReactDOM.render(<App />, document.getElementById('app'))
他声称这是ES6。
但是后来我看到了另一种创建组件的方法。
class App extends React.Component { render(){ return <h1>Hello</h1>; } }
嗯,我现在很困惑。是否有任何标准的反应方式?
在React中,您可以创建所谓的有状态和无状态功能组件。无状态组件是不需要维护状态的简单可重用组件。这是一个简短的演示(http://codepen.io/PiotrBerebecki/pen/yaoOKv),向您展示如何创建它们以及它们如何访问从父级传递的道具(有状态组件)。
一个简单的例子可能是AppFacebook.com上的理论状态组件。它可以保持状态以跟踪用户是登录还是注销。然后,在其render()方法中,它将显示一个LoginLogout无状态按钮组件,将其传递给当前状态。然后,LoginLogout无状态组件将显示:
App
render()
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') );