理解
1)state是组件对象最重要的属性,值是对象(可以包含多个 key-value 的组合)
2)组件被称为""状态机",通过更新组件的state来更新对应的页面显示(重新渲染组件)
注意
1)组件中render方法中的 this为组件实例对象;
2)组件自定义的方法中 this 为undefined,如何解决?
a.强制绑定this,通过函数对象的 bind()
b.箭头函数
3)state中的数据不能直接修改或更新,要使用setState方法。
标准写法:
注意:
1.函数的调用:onClick、onChange、...
2.this的使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>react-state</title>
</head>
<body>
<div id="root">
</div>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
class Weather extends React.Component {
constructor(props) {
super(props)
this.state = { hotOrCold: true, wind: '下雨了' }
this.changeWeather = this.changeWeather.bind(this)
}
render() {
console.log(this);
const { hotOrCold, wind } = this.state
return (
<div>
<h1>Hello, world!</h1>
<h2 onClick={this.changeWeather}>今天天气很{hotOrCold ? '炎热' : '凉爽'},但是{wind}</h2>
</div>
)
}
changeWeather() {
console.log(this);
const { hotOrCold } = this.state
this.setState({ hotOrCold: !hotOrCold })
}
}
ReactDOM.render(<Weather />, document.getElementById('root'))
</script>
</body>
</html>
简写:
1.不再使用构造器函数;
2.state直接在类中赋值;
3.类中的函数使用箭头函数来改变this指向;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>state的简写</title>
</head>
<body>
<div id="root">
</div>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
class Whoami extends React.Component {
state = { name: 'zmy' }
render() {
return (<div>
<div>我的名字是{this.state.name}</div>
<button onClick={this.changeName}>点我</button>
</div>)
}
changeName = () => {
this.setState({
name: '改变了name'
})
}
}
ReactDOM.render(<Whoami />, document.getElementById('root'))
</script>
</body>
</html>