1:父组件的render 流程
<script type="text/babel"> // 加上babel 语句可以将jsx 语法转化为js 语法
使用类定义组件
class Count eextends React.Component {
constructor () { // 构造器 组件挂载之前
// 数据初始化
this.state = {
count = 0;
}
}
}
// 定义A 组件
class A extends React.Component {
// 初始化数据
state = {
carName = "长城"
}
// 自定义事件 自定义事件 使用赋值语句 + 加上箭头函数
changeCar =()=> {
this.state({carName: "红旗"})
}
render() {
return { // 在return 对象中书写jsx 语法
<div>
<h3>A组件</h3>
<button @onClick={this.changeCar}>修改</button>
<B carName={this.state.carName}/>
</div>
}
}
}
// 定义B 组件
class B extends React.Component {
在子组件中有一个生命周期: componentWillReceiveProps
组件将要接受新的Props 钩子 --- 第一次接受props 的时候不会更新, 只有后来props 更新了。才会触
发。
componentWillReceiveProps(props) { props 参数就是父组件传递过来的参数
conssole.log(props---"props")
}
render() {
return {
<div>
<h3>B组件</h3>
在B 组件中就可以使用props 进行接受
<p>我的车是: {thi.props.carName}</p>
</div>
}
}
}
}
// 挂在组件到容器
ReactDOM.render(<A/>,document.getElementById('test'));
</script>
----------------------------------------------------------
注意: React生命周期中的componetWillReceiveProps的坑
在Raect 框架中 componentWillReceiveProps 在你的子组件第一次render 的时候是不会执行这个函数的。 只有在你的props 在第二次的时候才可以执行。 就是第二次render 时候才可以执行该函数。
React 生命周期总结:
一: 初始化阶段 (挂载阶段): 由ReactDOM.render() 触发一次 (初次渲染)
constructor: 构造器
componentWillMount() 组件挂载之前
render() 渲染函数 ===> render 函数渲染函数
componentDidMount() 组件挂载完毕
componentDidMount() ====> 常用
一般在这个钩子中做一些初始化的事情。 例如: 定时器开关, 发送网络请求, 订阅消息
二: 更新阶段; 有组件内部this.setState (修改状态) 或者父组件render 触发
1: shouldComponentUpdate() 组件是否应该被挂载
2: componentWillUpdate() 组件在更新执之前
3: render() {} render 函数
4: componentDidUpdate() 组件更新完毕
三: 卸载组件: 由ReactDOM.unmountComponentAtNode() 触发
1: 在componentWillUnmount() ====> 常用
一般在这个钩子函数中做一些收尾的事情, 例如: 关闭定时器, 取消订阅消息。