html、原生js、Vue和React中点击事件回调函数传参对比

342 阅读1分钟

1. html属性

<button onclick="!function testArgs() {console.dir(arguments)}()">test</button>

控制台输出:

1.webp

在html中直接传递事件回调函数不会自动传入任何参数

2. 原生js监听

<button id="btn">test</button>

<script>
  document.getElementById('btn').onclick = function() {console.dir(arguments)}
</script>

控制台输出: 2.webp DOM元素监听回调时会自动传入一个事件对象(addEventListener添加的回调传参情况相同)

3. Vue

new Vue({
  el: '#ele',
  template: `<button @click="testArgs">test</button>`,
  methods: {
    testArgs: function() {console.dir(arguments)}
  }
})

控制台输出: 3.webp 当回调函数后面不加括号时,会自动传入一个事件对象

new Vue({
  el: '#ele',
  template: `<button @click="testArgs($event, 'arg1')">test</button>`,
  methods: {
    testArgs: function() {console.dir(arguments)}
  }
})

控制台输出: 4.webp 当回调函数后面添加括号时,需要主动传参(括号内为空时,arguments长度为0)

4. React

var ele = document.getElementById('ele')
function testArgs() {console.dir(arguments)}
ReactDOM.render(<button onClick={testArgs}>test</button>, ele)

控制台输出: 5.webp 回调函数自动传入一个事件对象 与Vue不同的是,回调函数后面不能添加括号,否则会立刻执行 如果需要手动传参,可以包裹一层函数

function(event){testArgs(event, 1, 2)}