失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 菜比如我的漫漫react学习路(二)

菜比如我的漫漫react学习路(二)

时间:2020-02-15 00:32:13

相关推荐

菜比如我的漫漫react学习路(二)

基础部分学差不多了,说说state和props

state:

class listData extends ponent{

//es6 的 语法,详情请出门右转看ES6

constructor(...props){

super(...props)

}

//也就这个state这个没有用react自己的getInitialState

this.state = {

testState:1

}

//其他的react生命周期照样可以使用,不过,注意没有逗号~

componentDidMount(){

//code balabala

}

changeState(){

this.setState({

testState: ++ this.state.testState

},()=>{//这个是setState的第二个参数,也就是一个function,就是一个回调函数,在state修改完之后,你想做的事情就可以放在这里

console.log(this.state.testState)

})

}

render(){

return(

<div onClick = {this.changeState.bind(this)}>测试那么一下</div>

)

}

}

现在来说说props

除去redux里的,我现在用到的props,都是在父子组件之间传值

let Parent = React.createClass({

getInitialState({

return{

tabIndex:1

}

}),

render(){

return(

<div>

<Child parent = {this}/>//把需要传给子组件的东西放在这里,可以直接把父组件的this传给子组件

</div>

)

}

})

let Child = React.createClass({

render(){

return(

<div>{this.props.parent.state.tabIndex}</div> //this.props.parent取到的就是父组件传过来的this,父组件的this都拿到了,那么父组件里的其他东西也就可以拿到了。

)

}

})

如果觉得《菜比如我的漫漫react学习路(二)》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。