[英]React - passing a function to a child component does nothing
First I must say that I have looked at all the "Passing a function to a child component" on this site and did not find the solution to my problem. 首先,我必须说,我已经查看了此站点上的所有“将功能传递给子组件”,但是找不到解决我问题的方法。 I have a parent class:
我有一个家长班:
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()
And a child class: 还有一个儿童班:
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()
I want to pass the handleClick() function to the NewProjectModal Component through the props. 我想通过道具将handleClick()函数传递给NewProjectModal Component。 But when I click the button in NewProjectModal, nothing happens.
但是,当我单击NewProjectModal中的按钮时,没有任何反应。 I would like to make it execute the handleClick() from the ProjetcsMenu component.
我想让它执行ProjetcsMenu组件中的handleClick()。
No need to wrap your onClick function in an arrow function in the child. 无需将onClick函数包装在子级的箭头函数中。 Try changing this part in your child component, because now you are not actually calling the function you want:
尝试在子组件中更改此部分,因为现在您实际上并没有在调用所需的函数:
<button onClick={this.props.onClick}>Validate</button>
Also, you are binding the click function twice in the parent component: in constructor and when you pass it to the child component. 另外,您还要在父组件中绑定两次click函数:在构造函数中以及将其传递给子组件时。 Any one of those should be enough.
这些中的任何一个都应该足够。
at first no need to bind the function again here 首先,无需在此处再次绑定功能
<NewProjectModal onClick={this.handleClick.bind(this)} />
Also, Gleb Kost's suggestion is better for performance reasons 此外,出于性能方面的考虑,Gleb Kost的建议更好
Anyway this {()=> this.props.onClick}
is incorrect, should be {()=> this.props.onClick()}
or simply {this.props.onClick}
无论如何,此
{()=> this.props.onClick}
不正确,应为{()=> this.props.onClick()}
或仅仅是{this.props.onClick}
Should work! 应该管用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.