首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

React 组件,初学者笔记

函数式(Function)组件

http://www.css88.com/react/docs/components-and-props.html

组件名称以大写字母开始

所有React组件都必须是纯函数,并禁止修改其自身props

functionWelcome(props){

returnHello,{props.name};

}

constelement=;

ReactDOM.render(

element,

document.getElementById('root')

);

类组件

栗子1:

classClockextendsReact.Component{

constructor(props){// 唯一可以分配 this.state 的地方是构造函数

super(props);

this.state={

date:newDate(),

comments: []

};

}

componentDidMount(){// 挂载(mounting):第一次渲染DOM

this.timerID=setInterval(()=>this.tick(),1000); // 设置定时器,周期性的更新组件

fetchComments().then(response=>{// ----------1

this.setState({// 浅合并,只会完全替换 this.state.comments 的值,不会改变改变其他的值

comments:response.comments

});

});

}

componentWillUnmount(){// 卸载(unmounting):产生的DOM被销毁

clearInterval(this.timerID); // 销毁定时器

}

render(){

return(

Hello,world!

//// ----------- 2 // 替换

);

}

}

ReactDOM.render(

tick(){

this.setState({// 不要直接修改state(状态),要用 setState()代替

date:newDate()

});

}

document.getElementById('root')

);

state(状态)

不要直接修改state,要用 setState()代替,唯一可以分配 this.state 的地方是构造函数

state更新会被合并:浅合并 => 看栗子1 --- 1

state 更新可能是异步的

react 为了优化性能,可能将多个setState()调用合并为一次更新

因为 this.props 和 this.state 可能是异步更新的,你不能依赖他们的值计算下一个state

错误写法:this.setState()

正确写法

第一个参数:接收的前一个状态

第二个参数:应用更新时的props

this.setState((prevState,props)=>({

counter:prevState.counter+props.increment

})

);

数据向下流动(单向数据流)

一个组件可以选择将state向下传递,作为其子组件的props(属性)=> 栗子1 --- 2

functionFormattedDate(props){

}

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20180621G0LJ0Y00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券