React学习
JSX注意点
- CSS类名: className替代class
- JSX只能使用表达式,不能使用if等语句
- 类首字母大写
组件创建方式
函数创建(无状态)
function Compon(props){ return ({
<div>{props}</div>
})
}ES6 class创建,此时可以使用state存储数据
class Compon extends React.Component { constructor(){
}
fn = () => {}
}
父子组件通信
通过props
父传递给子组件props,子组件通过 this.props获取
<Child title={data}>子---> 父
通过事件传递,父组件传递给子组件一个函数,子组件通过
this.props.event(data)返回给父组件父组件: <Child bindCilck={this.bindChange}>
子组件:
this.props.bindCilck(data)state
给组件内部提供数据,通过setState({ data })进行修改,this.state.data进行数据访问,render中只读取state,不用来设置
组件生命周期
- constructor()
初始化数据,初始化state - componeWillMount()
组件被挂载到页面之前调用,不会重复触发渲染,可以使用setState() - render()
渲染组件到页面中,不要在render方法中调用 setState() 方法. - componentDidMount()
组件已经挂载到页面中,可以使用DOM对象,可以使用setState() - componentWillReceiveProps()
每当组件的props改变的时候,都会触发运行阶段的函数。
可以通过对比this.props和nextProps并在该方法中使用this.setState()处理状态改变,可能会陷入无限循环 - shouldComponentUpdate()
根据这个方法的返回值决定是否重新渲染组件,返回true重新渲染,否则不渲染,返回值为Boolean - componentWillUpdate()
组件将要更新
## 渲染问题 - 在state中的数据,如果改变了,会立即渲染,前提使用正确修改state方式
- setState是异步的,有个一个回调函数。
this绑定
最好是通过箭头函数,简单方便
fn = () => {}

浙公网安备 33010602011771号