react--獲取元素 && setState同步更新

1、獲取元素

import React,{Component} from 'react'
export default class UserAdd extends Component{
    constructor(){
        super();
    }
    handleSubmit=()=>{
        let name=this.refs.name.value;//獲取定義好的ref
        console.log(name);
    }
    render(){
        return(
            <form onSubmit={this.handleSubmit}>
                <div className="from-group">
                    <label htmlFor="name">姓名</label>
                    <input type="text" className="form-control" ref="name"/>//先給要獲取的dom定義一個ref
                </div>
                <div className="from-group">
                    <input type="submit" className="btn btn-primary"/>
                </div>
            </form>
        )
    }

}

2、setState同步更新

setState函數的第二個參數允許傳入回調函數,在狀態更新完畢後進行調用

this.setState({
      load: !this.state.load,
      count: this.state.count + 1
    }, () => {
      console.log(this.state.count);
      console.log('加載完成')
    });
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章