React的this指向和表单处理

this指向

  • 箭头函数
onchange() {
      this.setState({
        ...
      })
    }
  render() {
    return (
      <div>
        //使用箭头函数的this指向,让这个this指向render方法
        <button onClick={() => {this.onchange()}}>+1</button>
      </div>
    )
  }
  • 使用 function.prototype.bind()
constructor() {
    super()

    // 初始化 state
    this.state = {
      count : 0
    }

    // 使用 bind() 方法将事件处理程序的this和组件实例绑定到一起
    this.onChangeState = this.onChangeState.bind(this)
  }
  • 使用 class 实例方法
onChangeState = () => {
    this.setState({
      count : this.state.count + 1
    })
  }

  render() {
    return (
      <div>
        <h1>计算机: { this.state.count }</h1>
        <button onClick={this.onChangeState()}>+1</button>
      </div>
    )
  }

表单处理

  • 受控组件

    • React 将 state 和 表单元素中的 value 绑定到一起,由state 值的变化进行控制表单元素的变化

    • 使用步骤:

      • 在 state 添加一个状态,作为表单元素的 value 值
      state = {
          txt : ''
       }
      
      <input type="text" name='txt' value={this.state.txt} />
      • 在表单元素中绑定 change 事件,将表单元素的值 设置为 state 的值
      handleChange() {
          this.setState({
              txt : e.target.value
          })
      }
      <input type="text" name='txt' value={this.state.txt} onChange = {this.handleChange}/>
  • 非受控组件:借助 ref ,使用原生 DOM 方法来获取表单元素值

    • 调用 React.createRef() 方法创建一个 ref 对象
    constructor() {
        super()
        this.txtRef = React.createRef()
    }
    • 将创建好的 ref 对象添加到文本框中
    <input type = "text" ref = {this.txtRef} />
    • 通过ref 对象获取到文本框的值
    console.log(this.txtRef.current.value)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值