react 计数器之组件传参(父传子)

<!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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值