9. react - 表单

1. 受控组价: 由react的SetState() 来控制表单组件渲染,state是组件渲染的【唯一数据源】

通过一个案例来体验受控组件:

   1.  select 选中不能使用 selected 使用 value。 

   2. onChange 事件必须绑定

   3. 多个表单组件使用 name 属性来区分。 e.target.name

class FormControl extends React.Component {
  constructor (props) {
    super(props)

    this.state = {
      inputValue: '',
      textAreaValue: '',
      fruit: ''
    }

    this.handleChange = this.handleChange.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
  }
  handleSubmit (event) {
    console.log(event)
    event.preventDefault();
    console.log(event.target.stuName.value)
    console.log(event.target.marker.value)
    console.log(event.target.fruit.value)

    console.log(this.state.inputValue)
    console.log(this.state.textAreaValue)
    console.log(this.state.fruit)

  }
  handleChange (e) {
    console.log(e.target, "change")
    if (e.target.name == 'stuName') {
      this.setState({
        inputValue: e.target.value
      })
    }

    if (e.target.name == 'marker') {
      this.setState({
        textAreaValue: e.target.value
      })
    }

    if (e.target.name == 'fruit') {
      this.setState({
        fruit: e.target.value
      })
    }
    
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        名称: <input type="text" name="stuName" value={this.state.inputValue} onChange={this.handleChange}></input><br /><br />
        备注: <textarea name="marker" value={this.state.textAreaValue} onChange={this.handleChange}></textarea><br /><br />
        喜欢的水果:
        <select name="fruit" value={this.state.fruit} onChange={this.handleChange}>
          <option value="grapefruit">葡萄柚</option>
          <option value="lime">酸橙</option>
          <option value="coconut">椰子</option>
          <option value="mango">芒果</option>
        </select><br /><br />
        <input type="submit" value="提交" />
      </form>
    )
  }
}
ReactDOM.render(
  <FormControl />,
  document.getElementById('root')
)

2. 非受控组件 : 组件的值受用户决定,值存在dom对象节点中。

  1.  this.fileInput = React.createRef()  和  <input type="file" ref={this.fileInput} /> 绑定元素

  2. this.fileInput.current 获取元素

class FileInput extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.fileInput = React.createRef();
  }
  handleSubmit(event) {
    event.preventDefault();
    alert(
      `Selected file - ${this.fileInput.current.files[0].name}`
    );
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Upload file:
          <input type="file" ref={this.fileInput} />
        </label>
        <br />
        <button type="submit">Submit</button>
      </form>
    );
  }
}

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

 

posted @ 2020-06-04 19:02  monkey-K  阅读(173)  评论(0编辑  收藏  举报