![](/img/trans.png)
[英]passing function as a prop to child component in React throws error
[英]React - passing a function to a child component does nothing
首先,我必須說,我已經查看了此站點上的所有“將功能傳遞給子組件”,但是找不到解決我問題的方法。 我有一個家長班:
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()
我想通過道具將handleClick()函數傳遞給NewProjectModal Component。 但是,當我單擊NewProjectModal中的按鈕時,沒有任何反應。 我想讓它執行ProjetcsMenu組件中的handleClick()。
無需將onClick函數包裝在子級的箭頭函數中。 嘗試在子組件中更改此部分,因為現在您實際上並沒有在調用所需的函數:
<button onClick={this.props.onClick}>Validate</button>
另外,您還要在父組件中綁定兩次click函數:在構造函數中以及將其傳遞給子組件時。 這些中的任何一個都應該足夠。
首先,無需在此處再次綁定功能
<NewProjectModal onClick={this.handleClick.bind(this)} />
此外,出於性能方面的考慮,Gleb Kost的建議更好
無論如何,此{()=> this.props.onClick}
不正確,應為{()=> this.props.onClick()}
或僅僅是{this.props.onClick}
應該管用!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.