React:点击时获得 object
React: Getting an object on click
我有一个 object 数组,它作为 属性 传递给一个列表,该列表将它们映射到 <li>
。
我希望能够针对任何单个项目单击列表中的项目,并接收 object 然后将其分配给根组件的状态 - 这样我就可以传递它到另一个 child comp.
var Menu = React.createClass({
render: function() {
return (<ul>
{
this.props.posts.map(function(post){
return <li><a onClick={function(e){console.log(e)}}>{post.title}</a></li>
})
}
</ul>)
}
})
https://jsfiddle.net/nbenita/yxw1z42q/
谢谢!
将回调函数作为道具传递到您的 Menu
组件中,并使用 Function.prototype.bind()
部分应用相关的 post 对象作为参数:
已更新 fiddle:https://jsfiddle.net/yxw1z42q/2/
var Blog = React.createClass({
getInitialState: function() {
return {
selectedPost:this.props.posts[0]
};
},
onPostSelected: function(selectedPost) {
this.setState({
selectedPost: selectedPost
});
}
render: function() {
return (<div>
<Menu posts={this.props.posts} onClick={this.onPostSelected} />
<Post content={this.state.selectedPost} />
</div>)
}
})
var Menu = React.createClass({
render: function() {
return (<ul>
{
this.props.posts.map(function(post){
return <li><a onClick={this.props.onClick.bind(this, post)}>{post.title}</a></li>
}, this)
}
</ul>)
}
})
进一步阅读
我有一个 object 数组,它作为 属性 传递给一个列表,该列表将它们映射到 <li>
。
我希望能够针对任何单个项目单击列表中的项目,并接收 object 然后将其分配给根组件的状态 - 这样我就可以传递它到另一个 child comp.
var Menu = React.createClass({
render: function() {
return (<ul>
{
this.props.posts.map(function(post){
return <li><a onClick={function(e){console.log(e)}}>{post.title}</a></li>
})
}
</ul>)
}
})
https://jsfiddle.net/nbenita/yxw1z42q/
谢谢!
将回调函数作为道具传递到您的 Menu
组件中,并使用 Function.prototype.bind()
部分应用相关的 post 对象作为参数:
已更新 fiddle:https://jsfiddle.net/yxw1z42q/2/
var Blog = React.createClass({
getInitialState: function() {
return {
selectedPost:this.props.posts[0]
};
},
onPostSelected: function(selectedPost) {
this.setState({
selectedPost: selectedPost
});
}
render: function() {
return (<div>
<Menu posts={this.props.posts} onClick={this.onPostSelected} />
<Post content={this.state.selectedPost} />
</div>)
}
})
var Menu = React.createClass({
render: function() {
return (<ul>
{
this.props.posts.map(function(post){
return <li><a onClick={this.props.onClick.bind(this, post)}>{post.title}</a></li>
}, this)
}
</ul>)
}
})