【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>
        )
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM