Javascript React onClick 函数在渲染时触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33846682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:33:15  来源:igfitidea点击:

React onClick function fires on render

javascriptreactjsbuttononclickdom-events

提问by Stralos

I pass 2 values to a child component:

我将 2 个值传递给子组件:

  1. List of objects to display
  2. delete function.
  1. 要显示的对象列表
  2. 删除功能。

I use a .map() function to display my list of objects(like in the example given in react tutorial page), but the button in that component fires the onClickfunction, on render(it should not fire on render time). My code looks like this:

我使用 .map() 函数来显示我的对象列表(如反应教程页面中给出的示例),但该组件中的按钮在onClick渲染时触发该函数(它不应该在渲染时触发)。我的代码如下所示:

module.exports = React.createClass({
    render: function(){
        var taskNodes = this.props.todoTasks.map(function(todo){
            return (
                <div>
                    {todo.task}
                    <button type="submit" onClick={this.props.removeTaskFunction(todo)}>Submit</button>
                </div>
            );
        }, this);
        return (
            <div className="todo-task-list">
                {taskNodes}
            </div>
        );
    }
});

My question is: why does onClickfunction fire on render and how to make it not to?

我的问题是:为什么onClick函数会在渲染时触发以及如何让它不触发?

回答by Long Nguyen

Because you are calling that function instead of passing the function to onClick, change that line to this:

因为您正在调用该函数而不是将该函数传递给 onClick,所以将该行更改为:

<button type="submit" onClick={() => { this.props.removeTaskFunction(todo) }}>Submit</button>

=>called Arrow Function, which was introduced in ES6, and will be supported on React 0.13.3 or upper.

=>称为箭头函数,它是在 ES6 中引入的,将在 React 0.13.3 或更高版本上支持。

回答by Pete TNT

Instead of calling the function, bind the value to the function:

不是调用函数,而是将值绑定到函数:

this.props.removeTaskFunction.bind(this, todo)

MDN ref: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

MDN 参考:https: //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

回答by Brian Swisher

The value for your onClickattribute should be a function, not a function call.

您的onClick属性值应该是一个函数,而不是函数调用。

<button type="submit" onClick={function(){removeTaskFunction(todo)}}>Submit</button>

回答by olisteadman

For those not using arrow functions but something simpler ... I encountered this when adding parentheses after my signOut function ...

对于那些不使用箭头函数但更简单的东西......我在我的 signOut 函数后添加括号时遇到了这个......

replace this <a onClick={props.signOut()}>Log Out</a>

替换这个 <a onClick={props.signOut()}>Log Out</a>

with this <a onClick={props.signOut}>Log Out</a>... !

有了这个<a onClick={props.signOut}>Log Out</a>……!

回答by Vishal Bisht

JSX is used with ReactJS as it is very similar to HTML and it gives programmers feel of using HTML whereas it ultimately transpiles to a javascript file.

JSX 与 ReactJS 一起使用,因为它与 HTML 非常相似,它让程序员有使用 HTML 的感觉,但它最终会转换为 javascript 文件。

Writing a for-loop and specifying function as {this.props.removeTaskFunction(todo)} will execute the functions whenever the loop is triggered .

To stop this behaviour we need to return the function to onClick.

The fat arrow function has a hidden returnstatement along with the bind property. Thus it returns the function to OnClick as Javascript can return functions too!!!!!

编写一个 for 循环并将函数指定为 {this.props.removeTaskFunction(todo)} 将在触发循环时执行这些函数。

为了阻止这种行为,我们需要将该函数返回给 onClick。

胖箭头函数有一个隐藏的return语句和bind 属性。因此它将函数返回给 OnClick,因为 Javascript 也可以返回函数!!!!!!

Use -

用 -

onClick={() => { this.props.removeTaskFunction(todo) }}

which means-

意思是-

var onClick = function() {
  return this.props.removeTaskFunction(todo);
}.bind(this);

回答by sudo bangbang

JSX will evaluate JavaScript expressions in curly braces

JSX 将评估花括号中的 JavaScript 表达式

In this case, this.props.removeTaskFunction(todo)is invoked and the return value is assigned to onClick

在这种情况下,this.props.removeTaskFunction(todo)被调用并将返回值分配给onClick

What you have to provide for onClickis a function. To do this, you can wrap the value in an anonymous function.

你必须提供的onClick是一个函数。为此,您可以将值包装在匿名函数中。

export const samepleComponent = ({todoTasks, removeTaskFunction}) => {
    const taskNodes = todoTasks.map(todo => (
                <div>
                    {todo.task}
                    <button type="submit" onClick={() => removeTaskFunction(todo)}>Submit</button>
                </div>
            );
    return (
        <div className="todo-task-list">
            {taskNodes}
        </div>
        );
    }
});

回答by Seyhak Ly

I had similar issue, my code was:

我有类似的问题,我的代码是:

function RadioInput(props) {
    return (
    <div className="form-check form-check-inline">
        <input className="form-check-input" type="radio" name="inlineRadioOptions" id={props.id} onClick={props.onClick} value={props.label}></input>
        <label className="form-check-label" htmlFor={props.id}>{props.label}</label>
    </div>
    );
  }
class ScheduleType extends React.Component
{
    renderRadioInput(id,label)
    {
        id = "inlineRadio"+id;
        return(
            <RadioInput
                id = {id}
                label = {label}
                onClick = {this.props.onClick}
            />
        );

    }

Where it should be

应该在哪里

onClick = {() => this.props.onClick()}

in RenderRadioInput

RenderRadioInput 中

It fixed the issue for me.

它为我解决了这个问题。