likes
comments
collection
share

Day 37/100 React 事件传参方法

作者站长头像
站长
· 阅读数 25

(一)需求

最近在学习React,学到了React事件传参的方式,就记录一下。

(二)介绍

1、bind的形式传参

bind形式 参数在前
clickBtn = (params, event) => {
    console.log('[ event ] >', params, event)
    this.setState({ sum: params + 1 })
  }

<Button onClick={this.clickBtn.bind(this, this.state.sum)} type="primary">点击+1</Button>

2、箭头函数的形式传参

箭头函数 参数在后
clickBtnCount = (event, params) => {
    console.log('[ clickBtnCount ] >', event, params)
    this.setState({ count: params + 2 })
  }

<Button onClick={(e) => this.clickBtnCount(e, this.state.count)} type="primary">点击+2</Button>

(三)完成Demo

/*
 * @Author: ArdenZhao
 * @Date: 2022-04-13 15:48:04
 * @LastEditTime: 2022-04-13 16:23:15
 * @FilePath: /react-ts/src/components/react/6-enent-this.js
 * @Description: file information
 */
import React from 'react';
import "antd/dist/antd.css";
import { Button } from 'antd';

class SubComponent extends React.Component {
  // 挂载阶段
  constructor(props) {
    super(props);
    this.state = {
      name: 'Arden',
      sum: 1,
      count: 0,
    }
  }
  // bind 的形式,第一个参数是参数值,第二个参数是event
  clickBtn = (params, event) => {
    console.log('[ event ] >', params, event)
    this.setState({ sum: params + 1 })
  }
  clickBtnCount = (event, params) => {
    console.log('[ clickBtnCount ] >', event, params)
    this.setState({ count: params + 2 })
  }
  render() {
    return (
      <>
        <h2>事件传参</h2>
        <p>1、bind的形式传参_计数器:{this.state.sum}</p>
        <Button onClick={this.clickBtn.bind(this, this.state.sum)} type="primary">点击+1</Button>
        <br></br>
        <p>2、箭头函数的形式传参_计数器:{this.state.count}</p>
        <Button onClick={(e) => this.clickBtnCount(e, this.state.count)} type="primary">点击+2</Button>
      </>
    )
  }
}

function ReactParams(props) {
  return (
    <div>
      <h1>Learn, {props.name}</h1>
      <form>
        <SubComponent />
      </form>
    </div>
  );
}
export default ReactParams

写在最后的话

学习路上,常常会懈怠。

《有想学技术需要监督的同学嘛~》https://mp.weixin.qq.com/s/Fy...

如果有需要的伙伴,可以加我微信:learningisconnecting或者可以关注我的公众号:国星聊成长(我会分享成长的方法)
转载自:https://segmentfault.com/a/1190000041697996
评论
请登录