一、简单方法的创建和使用

class Home extends React.Component {
    constructor(props) {
        super(props)
    }

		// 1.创建方法
    run() {
        console.log('run ');
    }

    render() {
        return (
            <div>
            		// 2.调用方法
                <button onClick={this.run}>运行</button>
            </div>
        )
    }
}

二、获取state数据的几种方式(常用箭头函数法)

1. html-bind

2.构造函数bind

3.箭头函数 (常用)

4.完整例子

class Home extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            name: '张三',
            age: 20,
            sex: '男'
        }
        this.getAge = this.getAge.bind(this);
    }

    // 方式1
    getName() {
        console.log(this.state.name);
    }

    // 方式2
    getAge() {
        console.log(this.state.age);
    }

    // 方式3
    getSex = ()=> {
        console.log(this.state.sex);
    }

    render() {
        return (
            <div>
                {/* 方式1 */}
                <button onClick={this.getName.bind(this)}>获取数据 - 改变this指向1</button>
                <br /><br />

                {/* 方式2 */}
                <button onClick={this.getAge}>获取数据 - 改变this指向2</button>
                <br /><br />

                {/* 方式3 */}
                <button onClick={this.getSex}>获取数据 - 改变this指向3</button>
            </div>
        )
    }
}

三、在方法中修改state值

class Home extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            msg: '初始值',
        }
    }

    setData = ()=>{
        this.setState({
            msg: '我是改后值'
        })

    }

    render() {
        return (
            <div>
                <h1>我是home {this.state.msg}</h1>
                <button onClick={this.setData}>改变数据</button>
            </div>
        )
    }
}

四、方法传值

class Home extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            name: '张三',
        }
    }
    
    setName = (name) => {
        this.setState({
            name: name
        })
    }

    render() {
        return (
            <div>
                <h1>我是home {this.state.name}</h1>
                <button onClick={this.setName.bind(this, '李四')}>执行方法传值</button>
            </div>
        )
    }
}
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐