react数据双向绑定(记录)


class DataBinding extends React.Component {
    constructor() {
        super()
        this.state = {
            userName: '双向绑定'
        }
    }
    // --------------- e.target
    inputChange = e => {
        this.setState({
            userName: e.target.value
        })
    }
    getData = () => {
        alert(this.state.userName)
    }
    // ---------------- ref
    inputCha =() => {
        let val = this.refs.username.value
        this.setState({
            userName: val
        })
    }
    getUser = () => {
        alert(this.state.userName)
    }
    render() {
        return (
            <div>
                <input value={this.state.userName} onChange={this.inputChange}></input>
                <button onClick={this.getData}>点击获取</button>
                <p>{this.state.userName}</p>
                <input ref="username" value={this.state.userName} onChange={this.inputCha}/>
                <button onClick={this.getUser}>点击获取</button>
            </div>
        )
    }
}

 

posted @ 2020-03-11 20:49  印第安小铁匠  阅读(328)  评论(0编辑  收藏  举报