react表单-受控

react - 表单组件

受控组件

表单项中的值(value/checked)受到类组件state中数据来控制,同时还需要绑定一个onChange事件来完成对state中数据的修改

import React, { Component } from 'react';

class AppInput extends Component {
  // 设置受控组件
  state = {
    userName: '',
    passWord: '',
    userName2: '',
    passWord2: ''
  }
  changeName = event => {
    this.setState({
      userName: event.target.value.trim()
    })
  }
  changePassword = event => {
    this.setState({
      passWord: event.target.value.trim()
    })
  }
  clickHandler = () => {
    console.log(this.state)
  }
  
  setValue = event => {
    this.setState({
      [event.target.name]: event.target.value.trim()
    })
  }
  render() {
    const { userName, passWord, userName2, passWord2 } = this.state
    return (
      <div>
        <label >
          账号:
          <input type="text" value={userName} onChange={this.changeName} />
        </label>
        <br />
        <label >
          密码:
          <input type="passWord" value={passWord} onChange={this.changePassword} />
        </label>
        <br />
        <button onClick={this.clickHandler}>点击进入</button>

        <div>
          {/* 为了简化代码还可以使用对象签名来整合onchange事件 */}
          <label htmlFor="">
            账号:
            <input type="text" name='userName2' value={userName2} onChange={this.setValue} />
          </label>
          <br />
          <label htmlFor="">
            密码:
            <input type="passWord" value={passWord2} name='passWord2' onChange={this.setValue} />
          </label>
          <br />
          <button onClick={this.clickHandler}>点击进入</button>
        </div>
      </div>
    );
  }
}

export default AppInput;

为了体现react的灵活性,和方便组件拆分,还可以用一种高级写法

import React, { Component } from 'react';

const formState = _this => {
    return {
        userName: {
            value: '',
            onChange: event => _this.setState({
                // 下面是对state中的userName进行更新,展开获取所有的值,在修改更新后的value
                userName: { ..._this.state.userName, value: event.target.value }
            })
        },
        passWord: {
            value: '',
            onChange: event => _this.setState(state => ({
                // passWord : {..._this.state.passWord , value : event.target.value}
                passWord: Object.assign({}, state.passWord, { value: event.target.value.trim() })
            }))
        }
    }
}
class AppInput02 extends Component {
    state = {
        // userName : {
        //     value : '',
        //     onChange : event => this.setState({
        //         // 下面是对state中的userName进行更新,展开获取所有的值,在修改更新后的value
        //         userName : {...this.state.userName , value : event.target.value}
        //     })
        // },
        // passWord : {
        //     value : '',
        //     onChange : event => this.setState({
        //         passWord : {...this.state.passWord , value : event.target.value}
        //     })
        // }

        //这样写就是为了方便将代码提取
        ...formState(this)
    }
    clickhandler = () => {
        console.log(this.state)
    }
    render() {
        const { userName, passWord } = this.state
        return (
            <div>
                <label >
                    账号:
                    <input type="text" {...userName} />
                </label>
                <label >
                    密码:
                    <input type="passWord" {...passWord} />
                </label>
                <button onClick={this.clickhandler}>点击进入</button>
            </div>
        );
    }
}

export default AppInput02;

案例: 全选按钮

import React, { Component } from 'react';

class AppInput03 extends Component {
    state = {
        option: ['html', 'css', 'js', 'vue', 'react'],
        selection: [],
        selectAll : false
    }
    selection = e=> {
        console.log(e.target.value , e.target.checked)
        let value = e.target.value
        // 通过给单选框绑定一个value,在改变的时候通过这个值判断改变的是哪一个input ,并将选中与否的结果用是否选中数组中是够存有值来相关联
        if(e.target.checked){
            this.state.selection.push(value)
            this.state.selectAll = this.state.selection === this.state.option

        }else{
            this.state.selection = this.state.selection.filter(itm => itm !== value)
            // this.state.selectAll = this.state.selection === this.state.option
            this.state.selectAll = false
        }
        // 别忘了渲染
        // this.setState({})
        this.forceUpdate()
    }
    clickHandler =()=> {
        console.log(this.state)
    }
    // 控制是否全选,实际上就是selection数组中是否包含了全部的option数组选项
    selectAll = (e)=>{
        this.state.selectAll = e.target.checked
        if(e.target.checked){
            this.state.selection = this.state.option
        }else{
            this.state.selection = []
        }
        this.forceUpdate()
    }
    render() {
        const { option, selection ,selectAll } = this.state
        return (
            <div>
                <label >
                    全选:
                <input type="checkbox"  checked={selectAll} onChange={this.selectAll}/>
                </label>
                <div>
                    <ul>
                        {/* 在使用state中结构出来的值时,一定要加{} , 为啥老是忘记*/}
                       {option.map((itm , index) => (
                        <li key={index}>
                            {/* 单选多选框中决定表单是否是受控组件的属性是 checked , */}
                            <input type="checkbox" value={itm} checked={selection.includes(itm)} onChange={this.selection}/>
                            <span>{itm}</span>
                        </li>
                       ))}
                    </ul>
                </div>
                <button onClick={this.clickHandler}>查看数据</button>
            </div>
        );
    }
}

export default AppInput03;

你可能感兴趣的:(react,react.js,javascript,前端)