javascript React.js:从子级到父级的 onClick 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31564776/
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-10-28 13:59:13  来源:igfitidea点击:

React.js: onClick function from child to parent

javascriptonclickreactjs

提问by user2787338

I used thisarticle as an example (React way), but it is not working for me. Please point me to my mistake, as I can't understand what's wrong.

我以这篇文章为例(React 方式),但它对我不起作用。请指出我的错误,因为我不明白出了什么问题。

This is the error I see:

这是我看到的错误:

Uncaught TypeError: this.props.onClick is not a function

未捕获的类型错误:this.props.onClick 不是函数

Here is my code:

这是我的代码:

// PARENT
var SendDocModal = React.createClass({
  getInitialState: function() {
    return {tagList: []};
  },
  render: function() {
    return (
      <div>
        {
          this.state.tagList.map(function(item) {
            return (
              <TagItem nameProp={item.Name} idProp={item.Id} onClick={this.HandleRemove}/>
            )
          })
        }
      </div>
    )
  },
  HandleRemove: function(c) {
    console.log('On REMOVE = ', c);
  }
});

// CHILD
var TagItem = React.createClass({
  render: function() {
    return (
      <span className="react-tagsinput-tag">
        <span>{this.props.nameProp}</span>
        <a className='react-tagsinput-remove' onClick={this.HandleRemove}></a>
      </span>
    )
  },
  HandleRemove: function() {
    this.props.onClick(this);
  }
});

Thanks in advance!

提前致谢!

回答by Felix Kling

The issue is that thisinside the mapcallback does not refer to the React component, hence this.HandleRemoveis undefined.

问题是回调this内部map没有引用 React 组件,因此this.HandleRemoveundefined.

You can set the thisvalue explicitly by passing a second argument to map:

您可以this通过向 传递第二个参数来显式设置值map

this.state.tagList.map(function() {...}, this);

Now thisinsidethe callback refers to the same value as thisoutsidethe callback, namely the SendDocModalinstance.

现在回调this内部引用与回调this外部相同的值,即SendDocModal实例。

This has nothing to do with React, it's just how JavaScript works. See How to access the correct `this` context inside a callback?for more info and other solutions.

这与 React 无关,它只是 JavaScript 的工作方式。请参阅如何在回调中访问正确的“this”上下文?了解更多信息和其他解决方案。

回答by AndrewB

Try the following:

请尝试以下操作:

    var SendDocModal = React.createClass({
        getInitialState: function() {

            var item = {};
            item.Name = 'First';
            item.Id = 123;

            var item2 = {};
            item2.Name = 'Second';
            item2.Id = 123456;
            return {tagList: [item,item2]};
        },

        HandleRemove: function(c){
            console.log('On REMOVE = ', c);
        },

        render: function() {
            return (<div>
                {this.state.tagList.map(function(item){
                    return(
                            <TagItem nameProp={item.Name} idProp={item.Id} key={item.Id} click={this.HandleRemove}/>
                    )}, this)}
                    </div>
            )       
        }

    });
    // CHILD
    var TagItem = React.createClass({

        handleClick: function(nameProp)
        {
            this.props.click(nameProp);
        },


        render: function(){
            return(
                <span className="react-tagsinput-tag" ><span onClick={this.handleClick.bind(this, this.props.nameProp)}>{this.props.nameProp}</span><a className='react-tagsinput-remove' ></a></span>
            )
        }
    }); 

Few changes:

一些变化:

Added 'this' after the tagList mapping. To be honest I am not entirely sure why - perhaps a more experienced programmer can tell us.

在 tagList 映射之后添加了“this”。老实说,我不完全确定为什么 - 也许更有经验的程序员可以告诉我们。

Added a key to each TagItem. This is recommended and an the console will inform you that you should do this so that if the state changes, React can track each item accordingly.

为每个 TagItem 添加了一个键。这是推荐的,控制台会通知你应该这样做,以便如果状态发生变化,React 可以相应地跟踪每个项目。

The click is passed through the props. See React js - having problems creating a todo list

点击通过道具传递。请参阅React js - 创建待办事项列表时遇到问题