组件容许咱们将UI拆分为独立的、可重用的部分,并独立地考虑每一个部分。数组
定义个组件的最简单的方式就是写一个Javascript函数。该函数接受一个对象做为参数(咱们称之为props,该参数为只读参数),而且返回一个React Element闭包
function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
2.2.1 组件类中的方法:app
2.2.2 组件类中的属性:
state:用于维护实例变量,全部的方法均可以访问该实例变量中的值。实际上这就组成了一个闭包。在使用state的时候须要明确几点dom
不要试图直接修改state的值,而是经过setState方法。只能在构造函数中对state进行赋值操做异步
// Wrong this.state.comment = 'Hello'; // Correct this.setState({comment: 'Hello'});
state状态的更新多是异步的,能够使用另一种方式修改state的值函数
// Correct this.setState((state, props) => ({ counter: state.counter + props.increment }));
2.2.3 数据流向下传递:this
2.2.4 类组件示例code
class Welcome extends React.Component { //构造函数,在构造函数第一行要调用super constructor(props){ super(props); this.state = {date:new Date()} } //组件绑定的时候设置间歇调用,每隔一秒钟修改date值 componentDidMount(){ this.timerID = setInterval( () => this.tick(), 1000 ); } //组件卸载时取消简写调用 componentWillUnMount(){ clearInterval(this.timerID); } //修改date值 tick(){ this.setState({ date: new Date() }); } //渲染,当state中的值发生变化的时候DOM中对应的值也会发生变化 render(){ return <h1>hello {this.state.date.toLocaleTimeString()}</h1> } } ReactDOM.render(<Welcome/>,document.getElementById('app'));
function Welcome(props){ return <h1>hello {props.name}</h1> } const dom = <Welcome name='terry'/> ReactDOM.render(dom, document.getElementById('app') );
//定义Welcome组件 function Welcome(props){ return <h1>hello {props.name}</h1> } //在App中使用Welcome组件 function App(props){ return ( <div> <Welcome name='terry'/> <Welcome name='larry'/> <Welcome name='tom'/> </div> ); } // const dom = <App/> ; ReactDOM.render( dom,document.getElementById('app'));