1. 组件介绍
组件允许我们将UI拆分为独立的、可重用的部分,并独立地考虑每个部分。
2. 组件定义
2.1. 函数组件
定义个组件的最简单的方式就是写一个Javascript函数。该函数接受一个对象作为参数(我们称之为props,该参数为只读参数),并且返回一个React Element
function Welcome(props) { returnHello, {props.name}
;}
2.2. 类组件
2.2.1 组件类中的方法:
- render() 主要渲染返回,用于返回一个React Component
- constructor(props) 构造函数方法,该方法中必须显式调用super(props)
- componentDidMount() 组件挂载时的钩子函数
- componentWillUnmount() 组件卸载时的钩子函数
2.2.2 组件类中的属性:
state:用于维护实例变量,所有的方法都可以访问该实例变量中的值。实际上这就组成了一个闭包。在使用state的时候需要明确几点-
不要试图直接修改state的值,而是通过setState方法。只能在构造函数中对state进行赋值操作
// Wrongthis.state.comment = 'Hello';// Correctthis.setState({comment: 'Hello'});
-
state状态的更新可能是异步的,可以使用另外一种方式修改state的值
// Correctthis.setState((state, props) => ({ counter: state.counter + props.increment}));
2.2.3 数据流向下传递:
2.2.4 类组件示例
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(){ returnhello {this.state.date.toLocaleTimeString()}
} } ReactDOM.render(,document.getElementById('app'));
4. 组件使用
4.1 组件定义好了,通过标签来调用组件,并且组件属性可以被设置到props中。
function Welcome(props){ returnhello {props.name}
} const dom =ReactDOM.render(dom, document.getElementById('app') );
4.2 组件嵌套使用
//定义Welcome组件 function Welcome(props){ returnhello {props.name}
} //在App中使用Welcome组件 function App(props){ return (); } // const dom =; ReactDOM.render( dom,document.getElementById('app'));