【问题标题】:React - passing a function to a child component does nothingReact - 将函数传递给子组件什么都不做
【发布时间】:2018-01-01 15:10:16
【问题描述】:

首先我必须说,我已经查看了此站点上的所有“将函数传递给子组件”,但没有找到解决问题的方法。 我有一个父类:

import React from 'react';
import $ from 'jquery';
import Project from './Project';
import NewProjectModal from './NewProjectModal';
/**
 * A projects menu
 */
class ProjectsMenu extends React.Component 
{
  constructor(props) 
  {
    super(props);
    var projects = [];
    this.state = {_projects : projects};
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(e) {
    e.preventDefault();
    console.log("Hello there");
  }


  render() 
  {    
    return (
    <div className="column">
      {/*problem here:*/}
      <NewProjectModal onClick={this.handleClick.bind(this)} />   

      <a id="new-project" className="trigger" onClick={()=>this.showNewProjectModal()}>New project</a><br/>
      {this.state._projects.map((item,index) => 
        <div key={index}>{item}</div>
      )}
    </div>  
  );
  }//render()

还有一个子类:

import React from 'react';
import $ from 'jquery';

/**
 * A modal for the new project
 */
class NewProjectModal extends React.Component {
  constructor(props) {
    super(props);
    console.log(this.props);
  }

  render() {
    return (
        <div id="new-project-modal">
          <div>
            <p>New Project</p>
            <input type="text" name="project-name"/><br/>
            <button onClick={()=> this.props.onClick}>Validate</button>
          </div>
        </div>
    );
  }//render()

我想通过 props 将 handleClick() 函数传递给 NewProjectModal 组件。但是当我单击 NewProjectModal 中的按钮时,什么也没有发生。我想让它执行 ProjetcsMenu 组件中的 handleClick()。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    无需将您的 onClick 函数包装在子级的箭头函数中。尝试在您的子组件中更改此部分,因为现在您实际上并没有调用您想要的函数:

    <button onClick={this.props.onClick}>Validate</button>
    

    此外,您在父组件中绑定了两次 click 函数:在构造函数中以及将其传递给子组件时。任何一个都应该足够了。

    【讨论】:

      【解决方案2】:

      这里不需要再次绑定函数

      &lt;NewProjectModal onClick={this.handleClick.bind(this)} /&gt;

      此外,出于性能原因,Gleb Kost 的建议更好

      反正这个{()=&gt; this.props.onClick}是不正确的,应该是{()=&gt; this.props.onClick()}或者干脆是{this.props.onClick}

      应该可以!

      【讨论】:

        猜你喜欢
        • 2020-06-19
        • 1970-01-01
        • 2017-06-18
        • 1970-01-01
        • 1970-01-01
        • 2019-06-25
        • 2018-07-02
        • 1970-01-01
        • 2021-01-28
        相关资源
        最近更新 更多