1. 程式人生 > >react雙向事件的繫結

react雙向事件的繫結

雙向繫結有三步,第一步,觸發onChange事件,第二步,拿到input裡的值,第三步,使用setState將拿到的值傳回到state中。

如何拿到input裡的值,可以有兩種方法,第一種方法是引數e,由於每當觸發一個事件的同時,都會有一個引數e產生,因此,onChange={(e)=>this.txtChange(e)},然後在e.target.value中獲取事件觸發後的值。

第二種方法是通過react中的refs獲取文字框中的值,this.refs.自己定的名字.value,該方法獲取文字框中的值。

 

import React, { Component } from 'react';
class New extends Component {
    constructor(props){
        super(props)
        
this.state={ Name:'王一', Acount:'第二種獲取資料的方法' } } change=(e)=>{ // console.log('onChange事件就直接引用this就可以了,'+e.target.value) const data=e.target.value; this.setState({ Name:data, },function(){ console.log(
this.state.Name); } ) } changeTwo=()=>{ console.log(this.refs.txt2.value) } render(){ return<div> <h3>文字框的雙向繫結</h3> <h4>this.state.Name</h4> <input type='text' style={{width:'60%',height:'50%'}} value
={this.state.Name} onChange={this.change}/> <input type='text' style={{width:'60%',height:'50%'}} value={this.state.Acount} onChange={this.changeTwo} ref='txt2'/> </div> } } export default New;