React的新功能,我很难从食谱列表中选择一个项目。我正在研究如何从列表中删除配方,但首先我想弄清楚如何选择特定配方。
以下是一个运作良好的演示示例:
https://www.freecodecamp.com/challenges/build-a-recipe-box
正如您所看到的,每个项目都有自己的删除按钮,我也在我的代码中完成了。
我的容器中有以下代码:
的src /容器/ recipebox.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { ListGroup, ListGroupItem, Panel, Button, Modals } from 'react-bootstrap'
import { bindActionCreators } from 'redux';
import { deleteRecipe } from '../actions/index';
class RecipeBox extends Component {
constructor(props){
super(props);
this.state = {
open: false
};
this.renderRecipeList = this.renderRecipeList.bind(this)
}
renderRecipeList(recipeItem,index){
const recipe = recipeItem.recipe;
const ingredients = recipeItem.ingredients;
return(
<div key={index}>
<Panel bsStyle="primary" collapsible header={<h3>{recipe}</h3>}>
<ListGroup >
<ListGroupItem header="Ingredients"></ListGroupItem>
{ingredients.map(function(ingredient,index){
return <ListGroupItem key={index}>{ingredient}</ListGroupItem>;
})}
<ListGroupItem>
<Button
onClick={this.props.deleteRecipe}
value={recipeItem}
bsStyle="danger">Delete
</Button>
<Button
onClick={() => console.log('EDIT!')}
bsStyle="info">Edit
</Button>
</ListGroupItem>
</ListGroup>
</Panel>
</div>
)
}
render(){
return(
<div className="container">
<div className='panel-group'>
{this.props.addRecipe.map(this.renderRecipeList)}
</div>
</div>
)
}
}
function mapStateToProps(state) {
return {
addRecipe : state.addRecipe
};
}
function mapDispatchToProps(dispatch){
return bindActionCreators({deleteRecipe : deleteRecipe}, dispatch)
}
export default connect(mapStateToProps,mapDispatchToProps)(RecipeBox);
我的行动如此:
的src /动作/ index.js
export const RECIPE_ADD = 'RECIPE_ADD';
export const RECIPE_EDIT = 'RECIPE_EDIT';
export const RECIPE_DELETE = 'RECIPE_DELETE';
export function addRecipe(recipe) {
return {
type: RECIPE_ADD,
payload: recipe
}
}
export function editRecipe(recipe) {
return {
type: RECIPE_EDIT,
payload: recipe
}
}
export function deleteRecipe(event) {
return {
type: RECIPE_DELETE,
payload: event.target.value
}
}
具体来说,我在容器中看到了这个:
<Button
onClick={this.props.deleteRecipe}
value={recipeItem}
bsStyle="danger">Delete
</Button>
在我的减速机中,我看到了
payload: "[object Object]"
如何使用onClick事件侦听器从列表中选择适当的配方?
(注意:我还没有实现减速器,我只想看看我如何看到action.payload成为选定的配方)
编辑: 我找到了解决方案。简单地说,我需要弄清楚如何使用onClick传递参数而不需要自己调用。 以下ES6代码可以解决问题:
<Button
onClick={() => this.props.deleteRecipe(recipeItem)}
bsStyle="danger">Delete
</Button>
干杯
答案 0 :(得分:2)
我找到了解决方案。简单地说,我需要弄清楚如何使用onClick传递参数而不需要自己调用。以下ES6代码可以解决问题:
<Button
onClick={() => this.props.deleteRecipe(recipeItem)}
bsStyle="danger">Delete
</Button