简体   繁体   English

为什么按钮点击事件会在页面加载时自动触发-React.js

[英]Why button click event triggered automatically on page load - React.js

The following is the sample code written in React.js . 以下是用React.js编写的示例代码。

I am aware that passing the function to onClick event instead of calling the function can resolve this issue. 我知道将函数传递给onClick事件而不是调用函数可以解决此问题。

But what I can't understand is why onClick event is triggered on page load itself and prompting the alert by invoking the handleRemoveAll() method. 但是我不明白的是为什么在页面加载本身上触发onClick事件并通过调用handleRemoveAll()方法来提示警报。 Is this due to this.handleRemoveAll() is invoked at the global context? 这是由于this.handleRemoveAll()global上下文中调用吗? I am trying to understand how react.js works. 我试图了解react.js工作原理。

class IndecisionApp extends React.Component {
  render() {
      const options = ['One', 'Two', 'Three'];
      return (
        <div>
            <Options options={options}/>
        </div>
      )
  }
}
class Options extends React.Component {
    handleRemoveAll() { 
        alert('Are you sure you want remove all?');
    };
    render() {
       return (
            <div>
                <button onClick={this.handleRemoveAll()}>Remove All</button>
                {
                    this.props.options.map((option) => <Option key={option} optionText={option} />)
                }
            </div>
        )
    }
}
ReactDOM.render(<IndecisionApp />, document.getElementById('app'));

The onClick expects a function object, not a function call. onClick需要一个函数对象,而不是一个函数调用。 This is same as assigning a function Vs assigning its return value. 这与分配功能Vs分配其返回值相同。

function foo(){
   return 5*5;
}

1) var obj = foo; 1) var obj = foo; 2) var obj = foo(); 2) var obj = foo();

In case 1, you are assigning the function and in case 2 you are assigning the return value of foo(), ie, 25. So in case 2 like the above snippet the function will be called. 在情况1中,您要分配函数,在情况2中,您要分配foo()的返回值,即25。因此,在情况2中,如上述代码片段,将调用该函数。

In reactJs if you write the function directly in component it means "this" keyword is refer to window. 在reactJs中,如果直接在组件中编写函数,则意味着“此”关键字是指window。 and that's why it's loading while page load. 这就是为什么它在页面加载时加载。

So, try the below thing: 因此,请尝试以下操作:

  • make a constructor method into component and then bind the function which you created. 将一个构造函数方法放入组件,然后绑定您创建的函数。
  • And also use "this" keyword while making function. 并且在创建函数时也使用“ this”关键字。

I hope i did understood your question proper though you can try below suggestion or make clear your question. 我希望我确实理解您的问题,尽管您可以尝试以下建议或明确您的问题。

constructor(props) {
        super(props);
this.handleRemoveAll = this.handleRemoveAll.bind(this);
    this.handleRemoveAll = () => { 
        alert('Are you sure you want remove all?');
    };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM