3.react 方法、获取state值,修改state值,方法传参

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

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>
        )
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值