state 特点1:单向绑定,state变化视图自动更新,视图变化state不更新的 特点2:单向数据流,数据只能向下传递 特点3:state不能直接修改,要使用 this.setState()来修改 特点4:this.setState()是异步的,但在定时器里是同步的 特点5:多个this.setState()同时发生时,会被react合并成一个this.setState({}) 通过{this.add.bind(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>Document</title>
</head>
<body>
<!-- 准备容器 -->
<div id="test"></div>
<div id="test1"></div>
<!-- 引入React核心库 -->
<script src="https://unpkg.com/react@16/umd/react.production.min.js" crossorigin></script>
<!-- 引入React-DOM -->
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js" crossorigin></script>
<!-- 引入babel,将jsx转换为js -->
<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 = {
isHot: false,
wind: '微风'
}
// this.changeWeather = this.changeWeather.bind(this)
}
render () {
let { isHot, wind } = this.state
return (
<h1 onClick={ this.changeWeather.bind(this) }> { isHot ? '炎热': '凉爽'}, { wind }</h1>
)
}
changeWeather() {
// console.log(this)
let { isHot } = this.state
this.setState({
isHot: !isHot
})
}
}
ReactDOM.render(<Weather/>, document.getElementById('test'))
</script>
</body>
</html>
说明:
- this.changeWeather = this.changeWeather.bind(this) 可以通过这里的bind改变this的指向问题
- 写法二:
<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>Document</title>
</head>
<body>
<!-- 准备容器 -->
<div id="test"></div>
<div id="test1"></div>
<!-- 引入React核心库 -->
<script src="https://unpkg.com/react@16/umd/react.production.min.js" crossorigin></script>
<!-- 引入React-DOM -->
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js" crossorigin></script>
<!-- 引入babel,将jsx转换为js -->
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
class Weather extends React.Component {
state = {
isHot: false,
wind: '微风'
}
render () {
let { isHot, wind } = this.state
return (
<h1 onClick={ this.changeWeather }> { isHot ? '炎热': '凉爽'}, { wind }</h1>
)
}
changeWeather = () => {
// console.log(this)
let { isHot } = this.state
this.setState({
isHot: !isHot
})
}
}
ReactDOM.render(<Weather/>, document.getElementById('test'))
</script>
</body>
</html>
本篇结束 End!!!
|