iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 12
0
Modern Web

30天React從入門到入坑系列 第 12

DAY12:Form Uncontrolled Component

  • 分享至 

  • xImage
  •  

react非控制元件(Uncontrolled Component),基本上就跟一般的Html form很像,值不受state初使也沒有change callback管控。透過ref可以直接從DOM form取值,但無法像控制元件的同步效果,輸入透過callback setState再重新描繪UI,一切回歸傳統form操作。

src/FormRef.js

import React, { Component } from 'react';

class FormRef extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    console.log(this._name.value);
    //console.log(this.refs.name.value);
    e.preventDefault();
  }

  render() {

    return (
      <form onSubmit={this.handleSubmit} >
        <p>
          <label>
            name:
            <input type="text"  ref={input => this._name = input} />
            {/*
            <input type="text"  ref="name" />
            */}
          </label>
        </p>
        <input type="submit" value="submit" />
      </form>
    );
  }
}

export default FormRef;
src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import FormRef from './FormRef';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<FormRef />, document.getElementById('root'));
registerServiceWorker();

參考資料:
Controlled and uncontrolled form inputs in React don't have to be complicated
https://goshakkk.name/controlled-vs-uncontrolled-inputs-react/


上一篇
DAY11:Form Controlled Component
下一篇
DAY13:React write css 4 way
系列文
30天React從入門到入坑30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言