我试图实现一种变通方法,该方法基于if条件在主函数中调用两个函数。主要功能是切换onClick / onChange事件处理程序。
fetchData = command => e => {
if (e.target.tagName === "BUTTON") {
console.log("Button Clicked!");
this.setState({
command
});
this.ButtonData = command => {
console.log(command, "command received");
};
} else if (e.target.tagName === "INPUT") {
console.log("Input Clicked!");
this.setState({
command
});
this.InputData = command => {
console.log(command, "command received");
};
}
};
该代码仅在第一个控制台打印,“单击”后才起作用,但随后不会在if条件中调用的函数内进行。
以下是有效的沙箱:https://codesandbox.io/embed/pensive-bash-fmmmd
请帮助实现相同目标。
答案 0 :(得分:2)
这是正确的方法,请尝试将其粘贴到您的示例中:
import React, { Component } from "react";
export default class extends Component {
constructor() {
super();
this.state = {
command: "",
text_start: "enter text one",
text_end: "enter text two"
};
}
componentDidMount() {
this.fetchData();
}
buttonData = command => {
console.log(command, "command received");
};
inputData = command => {
console.log(command, "command received");
};
fetchData = command => e => {
if (e.target.tagName === "BUTTON") {
console.log("Button Clicked!");
this.setState({
command
});
this.buttonData(command);
} else if (e.target.tagName === "INPUT") {
console.log("Input Clicked!");
this.setState({
command
});
this.inputData(command);
}
};
render() {
return (
<>
<div>
<button value="start" onClick={this.fetchData("start")}>
Start
</button>
<button value="stop" onClick={this.fetchData("stop")}>
Stop
</button>
</div>
<div>
<input
type="text"
name="start"
value={this.state.text_start}
onChange={this.fetchData("e")}
/>
<input
type="text"
name="end"
value={this.state.text_end}
onChange={this.fetchData("e")}
/>
</div>
</>
);
}
}