react中onclick=”this.function”,function后面为什么不能加(),好像一加()就会自动执行
时间: 2023-02-20 22:17:26 浏览: 53
在 React 中,如果你写 `onClick = "this.function()"`,它会在组件加载时立即执行函数,而不是等到点击按钮时再执行。
因此,React 中的事件处理函数通常是以箭头函数的形式写在 `onClick` 属性中,例如:
```
<button onClick={() => this.function()}>Click me</button>
```
这样,当点击按钮时,函数才会被执行。
相关问题
react中onclick=”this.function”,前面为什么需要加this?
在 React 中,使用 `this` 来访问当前组件的实例。当使用箭头函数作为事件处理函数时,不需要使用 `this`。但是,使用普通函数作为事件处理函数时,需要使用 `this` 来访问组件的实例,以便访问组件的状态和其他方法。
例如:
```
class Example extends React.Component {
handleClick() {
console.log('Button was clicked');
}
render() {
return (
<button onClick={this.handleClick}>
Click me
</button>
);
}
}
```
如果不使用 `this`,则会抛出错误:
```
Uncaught TypeError: this.handleClick is not a function
```
在 React 中,如果你写 onClick = "this.function()",为什么会在组件加载时立即执行函数
在 React 中,如果你写了 onClick = "this.function()",这会在组件加载时立即执行该函数,因为它相当于在组件的 HTML 元素上直接执行该函数,而不是当点击事件发生时才调用该函数。
正确的方法是将函数作为事件处理程序绑定到组件:
```
<button onClick={this.function}>Click me</button>
```
或使用箭头函数:
```
<button onClick={() => this.function()}>Click me</button>
```
这样,当点击按钮时,才会执行该函数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
function TestFather() { const [on, setOn] = useState(false) function handleChildClick(value) { console.log(value) if (value === true) { setOn(true) } else { setOn(false) } } function A() { return 1 } function B() { return 2 } return ( {on ? : } <TestChild onButtonClick={handleChildClick} /> ) } export default TestFather class TestChild extends React.Component { handleButtonClick = () => { this.props.onButtonClick(true) } render() { return <button onClick={this.handleButtonClick}>Click me</button> } } export default TestChild 报错
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)