React基础知识备忘
section-1
//react组件
export class Halo extends React.Component{
constructor(...args){
super(...args); //初始化父类构造函数
this.state={ //设置state
text:""
}
}
hello(ev){
this.setState({ //修改state
text:ev.target.value
})
}
render(){
return(
{/只能一个父元素包裹/}
{/事件大小写注意 onChange onClick/}
{this.state.text}
)
}
}
section-2
export class Halo extends React.Component{
constructor(...args){
super(...args);
this.state={
display:"block"
}
}
toggle(){
this.setState({
display:this.state.display==="none" ? "block":"none"
})
}
render(){
return(
{/class在JSX中需要改成className/}
{/行内样式需要加两个花括号/}
内容的显示和隐藏
)
}
}
section-3
export class Halo extends React.Component{
constructor(...args){
super(...args);
this.state={
h:0,
m:0,
s:0
};
setInterval(function(){
this.update();
}.bind(this),1000)
}
update(){
let date=new Date();
this.setState({
h:date.getHours(),
m:date.getMinutes(),
s:date.getSeconds()
})
}
componentDidMount(){
this.update();
}
render(){
return(
{this.state.h}:{this.state.m}:{this.state.s}
)
}
}
section-4
/react 生命周期/
componentWillMount() 创建前
componentDidMount() 创建后
componentWillUpdate() 更新前
componentDidUpdate() 更新后
componentWillUnMount() 销毁前
componentWillReceiveProps(nextProps){
// ???
}
shouldComponentUpdate(){
//返回boolean值 默认每次状态更改时重新渲染
//返回false componentWillUpdate(),render()和componentDidUpdate()将不会被调用
}
section-5
//组件的另一种写法 无状态state组件
//Es6 React.Component Es5 React.createClass 其他两种定义方式
let Item=function(props){
return
};
export class Halo extends React.Component{
constructor(...args){
super();
this.state={
arr:[1,2,3,4,5]
}
}
addItem(){
this.setState({
arr:this.state.arr.concat([Math.random()])
})
}
render(){
let result=[],arr=this.state.arr;
for(var i=0;i<arr.length;i++){
{/需要给每个Item增加unique key唯一标识/}
result.push(
}
return(
{result}
)
}
}

浙公网安备 33010602011771号