react实现数据的双向绑定

大概思路:

1、当输入框的值发生改变时触发事件iptchange
2、在iptchange内将输入框的值赋值到state
3、点击按钮触发事件clickfun
4、在clickfun内获取输入框的值

方法一: 通过event.traget获取输入框的值(event.target.value)

import React from 'react'

class Methods extends React.Component{
    constructor () {
        super();

        this.state = {
            msg: '通过触发事件展示'
        }
    }  
    
    iptChange = (event) => {
        this.setState({
            msg: event.target.value
        })
    }

    getChangeVal = () => {
        console.log(this.state.msg)
    }

    render () {
        return (
            <div>
                <h3>{this.state.msg}</h3>
                <input type="text" onChange={this.iptChange}/>
                <button onClick={this.getChangeVal}>获取输入框的值</button>
            </div>
        )
    }
}

export default Methods;

方法二:通过ref获取输入框的值(this.refs.name.value)

import React from 'react'

class Methods extends React.Component{
    constructor () {
        super();

        this.state = {
            msg: '通过触发事件展示'
        }
    }  
    
    iptChange = (event) => {
        let val = this.refs.name.value;
        this.setState({
            msg: val
        })
    }

    getChangeVal = () => {
        console.log(this.state.msg)
    }

    render () {
        return (
            <div>
                <h3>{this.state.msg}</h3>
                <input ref="name" type="text" onChange={this.iptChange}/>
                <button onClick={this.getChangeVal}>获取输入框的值</button>
            </div>
        )
    }
}

export default Methods;
发布了72 篇原创文章 · 获赞 17 · 访问量 4万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览