【react】input输入框可输入的最好实现方式

使用的是refs。react中输入框不能直接定义value。输入框是可变的,react会提示报错。需要使用的inChange事件(输入框内容被改变时触发)。

要定义输入框初始值,需要在componentDidMount中定义,不能在componentWillMount中定义,因为render之后才能取到refs的input。使用this.refs.input1.value="初始值"。

改变输入框内容时,不会触发render重渲染。性能比更新state好。

class Input extends React.Component{
    componentDidMount(){
        this.refs.input1.value="初始值"
    }
    change(){
        console.log(this.refs.input1.value)
    }
    render(){
        return (
            <div className="customForm">
                <input type="text" ref="input1" onChange={this.change.bind(this)} />
            </div>
        )
    }
}

 

posted @ 2019-06-06 12:00  herry菌  阅读(1786)  评论(0编辑  收藏  举报