React实现最简单的按钮点击

本文通过一个按钮点击示例,介绍了React应用中State与Props的基本使用方式。演示了如何在父组件中设置State,并通过Props传递给子组件,同时展示了按钮点击事件触发State更新的过程。

在进行react开发中,最常用的就是props和state。我们今天做一个按钮点击的例子,来说明下props和state分别用说明作用

1.在项目出口文件中,我们直接渲染Button01组件。

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';import Button01 from './button01.jsx';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<Button01 />, document.getElementById('root'));
registerServiceWorker();

2.button01.jsx代码

import React from 'react';
import Button02 from './button02'

class Button01 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            display: false
        }
    }

    render() {
        return (
            <div onClick={() => {
                this.setState({
                    display: false
                })
            }}>
                <Button02 display={this.state.display}/>
                <Button02 display={this.state.display}/>
                <Button02 display={this.state.display}/>
                <Button02 display={this.state.display}/>
                <Button02 display={this.state.display}/>
            </div>
        )
    }
}

export default Button01;

3.button02.jsx代码

import React from 'react';

class button extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            display: this.props.display
        }
    }

    componentWillMount() {
        console.log('componentWillMount-', this.state.display)
    }

    componentWillReceiveProps(nextProps) {
        console.log("->", nextProps.display);
        if (this.state.display) {
            this.setState({
                display: nextProps.display
            })
        }
    }

    render() {
        return (
            <div>
                <button onClick={() => {
                    this.setState({
                        display: !this.state.display
                    })
                }}>
                    点击

                    <div style={{
                        backgroundColor: 'green',
                        width: 50,
                        height: 50,
                        display: this.state.display ? 'block' : 'none'
                    }}>
                    </div>
                </button>
            </div>
        )
    }
}

export default button;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值