<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>组件传参(父传子)</title>
</head>
<body>
<h2>react-first-demo</h2>
<div id="app"></div>
<script src="./lib/babel.min.js"></script>
<script src="./lib/react.development.js"></script>
<script src="./lib/react-dom.development.js"></script>
<!-- 如果需要jsx语法生效 需要设置script的type -->
<script type="text/babel">
const {Component} = React;
// 通过class定义的组件可以用于自己的局部状态数据state
class Conter extends Component {
constructor(props) {
super(props);
this.state = {
count: 1,//计数器
};
console.log("初始化");
this.clickHandle = this.clickHandle.bind(this);
}
clickHandle() {
// 在react中如果要改变state中的值 需要通过setState触发
// setState是异步的
// setState接收第二个参数 state的值改变之后的回调函数
console.log(this)
// alert('点了')
this.setState({
count: this.state.count + this.props.step,
},
function () {
console.log(this)
console.log("当前state值改变完成")
this.props.toParent(this.state.count);
}
);
}
render() {
const {step} = this.props;
const {count} = this.state;
return (
<button onClick={this.clickHandle}>计数器(步长为{step}-{count})</button>
);
}
}
class App extends Component {
constructor(props) {
super(props);
this.cClick =this.cClick.bind(this);
this.state={
childCount:1,
};
}
cClick(fromCount){
this.setState(
{childCount:fromCount,}
);
console.log(
"计数器的值变了"
)
}
render() {
const {childCount}=this.state;
return (
<div>
<h1>当前的计数值:{childCount}</h1>
<h5>第一个计数器,步长为-2</h5>
<Conter step={2} toParent={this.cClick}/>
</div>
)
}
}
ReactDOM.render(<App/>, document.querySelector('#app'))
</script>
</body>
</html>
05-04
394
06-02
834
01-15
6719
08-23
602
06-01
305
04-07
620