前言
因为对java、python比较熟悉,所以阿简在学习JSX的时候,很多东西都是往那熟悉的东西去靠近,类比着学习,JSX小彩笔,只是分享自己的学习心得
一: props 关键字
- 先看一个例子:
class Welcome extends React.Component{
constructor(props){
super(props)
}
render(){
return <h1>Welcome this people :{this.props.name}</h1>
}
}
function ShowAllWelcome() {
return(
<div>
<Welcome name = "YFJ"></Welcome>
<Welcome name = "LXTW"></Welcome>
<Welcome name = "WZ"></Welcome>
<Welcome name = "WEC"></Welcome>
</div>
)
}
ReactDOM.render(
<ShowAllWelcome/>,
document.getElementById("root")
)
在ShowAllWelcome方法中,我们调用了组件Welcome ,并通过name传入了值,看下在Welcome组件中name是怎么使用的,可见是通过this.props.name去获取到其值的,为了再明显一点,我们把ShowAllWelcome 方法再加一个age字段
class Welcome extends React.Component {
constructor(props){
super(props)
}
render() {
return (
<div>
<h1>Welcome this people :{this.props.name}</h1>
<h1>this people age:{this.props.age}</h1>
</div>
)
}
}
function ShowAllWelcome() {
return (
<div>
<Welcome name="YFJ" age="24"></Welcome>
<Welcome name="LXTW" age="24"></Welcome>
<Welcome name="WZ" age="25"></Welcome>
<Welcome name="WEC" age="24"></Welcome>
</div>
)
}
ReactDOM.render(
<ShowAllWelcome />,
document.getElementById("root")
)
我们还是通过this.props.age取得值,可见,this.props的作用是用于组件之间传递值,从java的角度理解,props可以理解上一个组件ShowAllWelcome把需要传递的属性通过props传入Welcome的构造函数的,在构造函数中props就作为了Welcome 的一个成员变量,这个成员变量就含有所有需要传递的值(可以理解为一个整合的对象)
二: state关键字
- 先看一个例子:
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
this.handleClick = this.handleClick.bind(this)
}
handleClick(id) {
console.log("id = "+id)
this.setState(state=> ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
首先,顾名思义,state是状态的意思,可以理解为当前组件的状态,在上述例子中,我们在构造函数中定义了this.state = {isToggleOn: true} ,使用的时候是通过this.state.isToggleOn去调用的,我还要其他状态怎么办呢?this.state = {isToggleOn: true,xxx : "xxx"},然后调用的时候再this.state.xxx去取值,我们想改变状态怎么办?执行this.setState(),当前组件就会自动刷新(重新执行render方法),从java角度,state在构造函数中初始化,管理了所有的状态对象(上述例子中就是:isToggleOn),this.setState()可以更新该成员变量,同时我们的自定义控件会刷新
三: prevState关键字
该博主已经写的很详细了,可以参考:react的setState中的prevState是什么