2018年5月13日 星期日

表單 (React 16 四)

受控組件:值會自動更新
非受控組件:值不會自動更新

※非受控組件



class FormPractice1 extends React.Component {
    constructor(p) {
        super(p)
        this.handleSubmit = this.handleSubmit.bind(this)
    }
    
    handleSubmit(e) {
        e.preventDefault() // 阻止提交
        alert(this.fname.value)
        alert(this.fpassword.value)
        // document.getElementsByTagName("form")[0].submit() // 提交
    }
    
    render() {
        return ( 
            <form action="xxx" onSubmit={this.handleSubmit}>
                <input name="name" ref={i => this.fname = i} /> 
                <input type="password" name="password" ref={i => this.fpassword = i} /><br />
                <input type="submit" value="提交" />
            </form>
        )
    }
}
    
ReactDOM.render(<FormPractice1 />, document.querySelector("#div1"));




※受控組件



class FormPractice1 extends React.Component {
    constructor(p) {
        super(p)
        this.state = {
            name:'',
            pwd:''
        }
        this.handleSubmit = this.handleSubmit.bind(this)
        this.handleChangeName = this.handleChangeName.bind(this)
        this.handleChangePwd = this.handleChangePwd.bind(this)
    }
    
    handleSubmit(e) {
        e.preventDefault() //阻止提交
        alert(`名稱:${this.state.name}  密碼:${this.state.pwd}`)
        // document.getElementsByTagName("form")[0].submit() // 提交
    }
    
    handleChangeName(e) {
        this.setState({
            name:e.target.value
        })
    }
    
    handleChangePwd(e) {
        this.setState({
            pwd: e.target.value
        })
    }
    
    render() {
        return ( 
            <form action="xxx" onSubmit={this.handleSubmit}>
                <input name="name" value={this.state.name} onChange={this.handleChangeName} /> 
                <input type="password" name="password" value={this.state.pwd} onChange={this.handleChangePwd} /><br />
                <input type="submit" value="提交" />
            </form>
        )
    }
}
    
ReactDOM.render(<FormPractice1 />, document.querySelector("#div1"));

※如果不寫事件,鍵盤打不進去

※onChange 在 React 裡,只要打完字就馬上更新了

沒有留言:

張貼留言