【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