首页 > 其他 > 详细

React之this.refs, 实现数据双向绑定

时间:2019-12-11 14:56:34      阅读:109      评论:0      收藏:0      [点我收藏+]

1、实现数据双向绑定

  将input组件与this.state属性绑定,要么是readonly, 要么使用onChange事件;

  获取input元素的value值,有两种方式:

  1) e.target.value

  2)  this.refs.引用名称

import React from ‘react‘

export default class Hello6 extends React.Component {
    constructor() {
        super()
        this.state = {
            msg: ‘测试数据双向绑定‘
        }
    }
    render() {
        return <div>
            基于class创建组件, {this.props.id} + ‘--‘ + {this.props.name}
            <h4>{this.state.msg}</h4>
            {/* 将input组件与this.state属性绑定,要么是readonly, 要么使用onChange事件 */}
            <input type="text" name="msg" value={this.state.msg} onChange={ (e) => this.inputChangeHandler(e) } ref="btn" /><br/><br/>

            {/* 测试点击事件 */}
            <button id="btn" onClick={ () => this.myOnclickHandler(this.state.msg) }>测试点击事件</button>
            
            </div>
    }

    myOnclickHandler = (msg) => {
        console.log(msg)
        console.log(this.state.msg)
        this.setState({msg:‘msg被修改了。。。‘}, function () {
            console.log(this.state.msg)
        })
    }

    inputChangeHandler = (e) => {
        // 获取input的value属性的第一种方式
        // console.log(e.target.value)

        // 获取input的value属性的第二种方式
        // 使用ref获取元素的引用
        console.log(this.refs.btn.value)

        // 同步数据
        const newVal = e.target.value
        this.setState({msg: newVal}, function() {
            console.log("调用this.state完成同步数据")
        })
    }

}

React之this.refs, 实现数据双向绑定

原文:https://www.cnblogs.com/xy-ouyang/p/12022528.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!