我希望在单击菜单项时使用相同的事件处理程序。
在vanilla JavaScript中,事件处理程序&#39;这个&#39; value将指向元素,您只需使用<template>
<div :class="className" @click="onClick">
<span class="open">{{ openName }}</span>
<span class="close">{{ closeName }}</span>
</div>
</template>
<script>
'use strict';
export default {
props: {
value: {
default: true,
twoWay: true
},
size: {
type: String,
default: 'md中'
},
// blue red green orange
color: {
type: String,
default: 'red'
},
openValue: {
default: true
},
closeValue: {
default: false
},
openName: {
type: String,
default: 'ON'
},
closeName: {
type: String,
default: 'OFF'
},
disabled: {
type: Boolean,
default: false
}
},
computed: {
className() {
let {
value,
openValue,
closeValue,
size,
color,
disabled
} = this;
return {
'vue-switch': true,
'z-on': value === openValue,
'z-disabled': disabled,
['s-' + size]: true,
['c-' + color]: true
};
}
},
methods: {
onClick() {
let {
disabled,
value,
openValue,
closeValue
} = this;
if (!disabled) {
if (openValue === value) {
this.value = closeValue;
} else {
this.value = openValue;
}
}
}
}
}
</script>
,如何在React中完成。
clickHandler2和clickHandler3我想把它变成一个事件处理程序。唯一不同的是点击的元素。
代码如下:
this.id
答案 0 :(得分:1)
您可以传递event参数并使用其target
属性:
clickHandler2 (e) {
var id = e.target.id;
}
顺便提一句,this
就是class
。
示例:
class App extends React.Component{
constructor(props){
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e){
const {id, value} = e.target;
console.log('id is - ' + id + ' and the value is: ' + value);
}
render(){
return(
<div>
<input id="input1" placeholder="type something" onChange={this.handleChange} />
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>