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完成同步数据") }) } }
原文地址:https://www.cnblogs.com/xy-ouyang/p/12022528.html