props state render
- 当组件的state或props发生变化,render函数就会执行
- 当父组件的render函数重新执行时子组件的render也会被执行
父组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| import React, {Component, Fragment} from 'react' import Child from './child'
class Parent extends Component{ constructor(props) { super(props); //当组件的state或props发生变化,render函数就会执行 this.state = { content: "", }; this.handleInputChange = this.handleInputChange.bind(this); }
render() { console.log("render"); const { content } = this.state; return ( <Fragment> <div>parent</div> <input onChange={this.handleInputChange}/> <Child content={content}/> </Fragment> ); }
handleInputChange(e) { const value = e.target.value; this.setState(() => ({ content: value, })); } }
export default Parent
|
子组件:
1 2 3 4 5 6 7 8 9 10 11 12 13
| import React, {Component} from 'react'
class Child extends Component{ render() { console.log("child render") const { content } = this.props; return ( <div>{content}</div> ); } }
export default Child
|

虚拟Dom
1 2 3 4 5
| render() { //JSX->createElement->虚拟DOM(js对象)->真实的dom //return <div>item</div>; return React.createElement("div", {}, 'item') }
|
原理:
React会在内存中维护一个虚拟DOM树,对这个树进行读或写,实际上是对虚拟DOM进行。当数据变化时,React会自动更新虚拟DOM,然后将新的虚拟DOM和旧的虚拟DOM进行对比,找到变更的部分,得出一个diff,然后将diff放到一个队列里,最终批量更新这些diff到DOM中。
优点:
性能提升
跨端应用得以实现 React Native
ref使用
修改todolist代码
1 2 3 4 5 6 7 8 9 10 11 12 13
| <input id="insertArea" value={this.state.inputValue} onChange={this.handleInputChange} ref={(input) => {this.input = input}} /> handleInputChange(e) { //const value = e.target.value; const value = this.input.value; this.setState(() => ({ inputValue: value, })); }
|
this.input指向了<input/>
的dom节点
注意事项:
1 2 3 4 5 6 7 8 9 10 11
| <ul ref={(ul) => {this.ul = ul}}> {this.getToDoItem()} </ul> handleButtonClick(index) { this.setState((prevState) => ({ list: [...prevState.list, prevState.inputValue], inputValue: "", }), () => { console.log(this.ul.querySelectorAll("li").length) }); }
|
console.log(this.ul.querySelectorAll(“li”).length)
要在setState第二个参数后使用,由于setState是异步执行
所以如果不放在setState执行后调用会导致dom节点数获取不对
生命周期函数
定义:在某一时刻组件会自动调用的函数

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| //组件挂载到页面之前执行(render函数执行前) componentWillMount() { console.log("componentWillUnmount") } //组件挂载到页面之后执行(render函数执行后) componentDidMount() { console.log("componentDidMount") } //组件更新前执行 shouldComponentUpdate() { return true or false //当return false 时当前组件的值更新会被禁用 } //组件更新前shouldComponentUpdate后执行 componentWillUpdate() { console.log("componentWillUpdate") } //当一个组件从父组件接收参数 //如果这个组件第一次存在于父组件中,不会被执行 //如果这个组件之前存在于父组件中,才会被执行 componentWillReceiveProps() { console.log("child componentWillReceiveProps" ) } //当这个组件即将在页面中被剔除 componentWillUnmount() { console.log("child componentWillUnmount") }
|