2.2 组件实例的三大核心属性1: state
class Weather extends React.Component{
constructor(props) {
console.log('constructor');
super(props);
this.state = {
isHot : true,
wind : '微风'
};
this.changeWeather = this.changeWeather.bind(this);
}
changeWeather(){
console.log('changeWeather');
console.log(this);
console.log("此处修改isHot值");
const isHot = this.state.isHot;
this.setState({
isHot : !isHot
})
console.log(this.state.isHot);
}
render(){
console.log('render');
return <h1 onClick={this.changeWeather} id='title'>今天天气很{this.state.isHot ? '炎热' : '凉爽'}, {this.state.wind}</h1>
}
}
ReactDOM.render(<Weather/>, document.getElementById('container'))
class Weather extends React.Component{
state = {
isHot : true,
wind : '微风'
};
changeWeather = ()=>{
console.log(this);
const isHot = this.state.isHot;
this.setState({
isHot : !isHot
})
}
render(){
const {isHot, wind} = this.state;
return <h1 onClick={this.changeWeather} id='title'>今天天气很{isHot ? '炎热' : '凉爽'}, {wind}</h1>
}
}
ReactDOM.render(<Weather/>, document.getElementById('container'))
- 理解
- state 是组件对象最重要的属性,值是对象
- 组件被称为“状态机”,通过更新组件的state来更新对应的页面显示(重新渲染组件)
- 强烈注意
- 组件中render方法中的this为组件实例对象
- 组件自定义的方法中this为Undefined, 如何调用?
- 状态数据,不能直接修改或更新
2.2_补充
<button id="btn1">按钮1</button>
<button id="btn2">按钮2</button>
<button onclick="demo()">按钮3</button>
<script>
const btn1 = document.getElementById('btn1');
btn1.addEventListener('click', ()=> {
alert('按钮1被点击')
})
const btn2 = document.getElementById('btn2');
btn2.onclick = ()=>{
alert('按钮2被点击');
}
function demo(){
alert('按钮3被点击');
}
</script>
function demo(){
console.log(this);
}
demo();
const x = demo.bind({a:1, b:2})
x();
class Person{
constructor(name, age){
this.name = name;
this.age = age;
}
speak (){
console.log(this);
}
}
const p1 = new Person('tom', 10);
p1.speak();
const x = p1.speak;
x();
class Car {
constructor (name, price){
this.name = name;
this.price = price;
}
wheel = 4;
}
const c1 = new Car('奔驰', 199);
const c2 = new Car('宝马', 199);
console.log(c1);
console.log(c2);