实现这一目标的最佳方法是什么:
我有一个呈现行的父级:
< div className = "container" >
{this.state.rows.map(function(row, i) {
return <ProjectsRow row={row} key={i} />
}.bind(this))}
< /div>
和孩子:
return (
<ReactTransitionGroup transitionName="reactClass" transitionAppear={true}>
< div className = "row" >
{this.props.row.map(function(project) {
return < div className = "col-md-4 project" key={project.id} >
< div className="text-center img-container"> <img alt="logo" src={project.thumbnail} />< /div >
<h4 className="text-center">
< a className = "linkStyle1"
href = {'#/project/' + project.id} >
<i className="fa fa-angle-right"></i>{project.title}
</a>
< /h4>
< /div>
})}
< /div>
<hr />
</ReactTransitionGroup>
如何在onClick
上使用h4
关于子级并在父级中访问它。我只能通过jQuery实现这一点,我不应该这样做。
答案 0 :(得分:2)
您可以将回调传递给您的孩子
< div className = "container" >
{this.state.rows.map(function(row, i) {
return <ProjectsRow row={row} key={i} onClickCb={this.onClickChild} />
}.bind(this))}
< /div>
必须在您的父组件中定义onClickChild。
您的子组件可以将此回调附加到其h4 evenhandler
< div className = "col-md-4 project" key={project.id} >
< div className="text-center img-container"> <img alt="logo" src={project.thumbnail} />< /div >
<h4 className="text-center" onClick={this.props.onClickCb}>
< a className = "linkStyle1"
href = {'#/project/' + project.id} >
<i className="fa fa-angle-right"></i>{project.title}
</a>
< /h4>
< /div>
我希望这有帮助
答案 1 :(得分:1)
var Parent = React.createClass({
randomFunction : function () {
alert('randomFunction() called in Parent');
},
render : function () {
return (
<div>
<Child randomFunction={this.randomFunction} />
</div>
);
}
});
var Child = React.createClass({
render : function () {
return (
<div>
<button onClick={this.props.randomFunction}>Click me to trigger function in Parent</button>
</div>
);
}
});