首先,我必须说,我已经查看了此站点上的所有“将函数传递给子组件”,但没有找到解决我的问题的方法。我有一个父类:
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 中的按钮时,没有任何react。我想让它从 ProjetcsMenu 组件执行 handleClick()。