Javascript React:将函数传递给子组件

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

React : Pass function to child component

javascriptreactjs

提问by onedkr

I try to pass a function to my child component. For each child component when the user click on them, the onclick function will be call. This onclick function is written into the parent component.

我尝试将一个函数传递给我的子组件。对于每个子组件,当用户单击它们时,将调用 onclick 函数。这个 onclick 函数被写入到父组件中。

Parent component:

父组件:

class AgentsList extends React.Component {
  constructor(props) {
    super(props);
  }

  handleClick(e) {
    e.preventDefault();
    console.log(this.props);
  }

  render() {
    const { agents } = this.props;

    ...

    var agentsNodes = agents.map(function(agent, i) {
      if(agent.id_intervention == "") {
        return (
          <Agent agent={agent} key={i} ticket={t} id={row_names} onClick={this.handleClick.bind(this)} />
        );
      }
    });
    return (
      <div id="agents">
        <div className="agents-title">
          <h3>Title</h3>
        </div>
        {agentsNodes}
      </div>
    );
  }
}

Child component:

子组件:

class Agent extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const { agent, t } = this.props;

    return (
      <Link to='/' onClick={this.props.onClick}>
        ...
      </Link>
    );
  }
}

At this line : <Agent agent={agent} key={i} ticket={t} id={row_names} onClick={this.handleClick.bind(this)} />

在这一行: <Agent agent={agent} key={i} ticket={t} id={row_names} onClick={this.handleClick.bind(this)} />

It say that handleClick is not defined ... How can I sovle this problem ?

它说 handleClick 没有定义......我该如何解决这个问题?

Thank's for your answer.

感谢您的回答。

回答by omarjmh

You need to bind Agents to AgentsList: Here's a quick example with your code, I had to get rid of some stuff, but you get the idea:

您需要将 Agents 绑定到 AgentsList:这是您的代码的一个快速示例,我不得不删除一些东西,但您明白了:

http://jsfiddle.net/vhuumox0/19/

http://jsfiddle.net/vhuumox0/19/

var agentsNodes = agents.map(function(agent, i) {
  if(agent.id_intervention == "") {
    return (
      <Agent agent={agent} key={i} ticket={t} id={row_names} onClick={this.handleClick.bind(this)} />
    );
  }
}, this); // here