zoukankan      html  css  js  c++  java
  • React之this.refs, 实现数据双向绑定

    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/> */}
           <input type="text" name="msg" value={this.state.msg} onChange={ (e) => this.inputChangeHandler(e) } ref={input=> this.msgInputObj = input} /><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)
         // 获取input的value属性第三种方式
         console.log(this.msgInputObj.value)
    // 同步数据 const newVal = e.target.value this.setState({msg: newVal}, function() { console.log("调用this.state完成同步数据") }) } }
  • 相关阅读:
    java中传值与传引用
    microsofr visual studio编写c语言
    openfile学习笔记
    在 Windows 和 Linux(Gnome) 环境下 从命令界面打开网页的方式
    使用vsphere client 克隆虚拟机
    route命令
    linux rpm问题:怎样查看rpm安装包的安装路径
    【leetcode】415. 字符串相加
    【leetcode】面试题 17.01. 不用加号的加法
    【leetcode】989. 数组形式的整数加法
  • 原文地址:https://www.cnblogs.com/xy-ouyang/p/12022528.html
Copyright © 2011-2022 走看看