React:将功能传递给子组件 [英] React : Pass function to child component
问题描述
我尝试将一个函数传递给我的子组件.当用户单击每个子组件时,将调用onclick函数.此onclick函数将写入父组件.
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.
父组件:
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>
);
}
}
子组件:
class Agent extends React.Component {
constructor(props) {
super(props);
}
render() {
const { agent, t } = this.props;
return (
<Link to='/' onClick={this.props.onClick}>
...
</Link>
);
}
}
在此行:<代理agent = {agent}键= {i}票证= {t} id = {row_names} onClick = {this.handleClick.bind(this)}/> 代码>
它说handleClick未定义...我该如何解决这个问题?
It say that handleClick is not defined ... How can I sovle this problem ?
谢谢您的回答.
推荐答案
您需要将Agent绑定到AgentsList:这是您的代码的一个简单示例,我不得不删除一些东西,但是您明白了:
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:
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
这篇关于React:将功能传递给子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!