Передача функции, которая принимает аргумент через несколько слоев в React - PullRequest
0 голосов
/ 09 июня 2018

Моя цель - передать функцию deleteRecipe (которая принимает аргумент) через компонент Recipe, который затем передается компоненту Button.Я застрял с задачей передачи индекса / идентификатора рецепта к исходной функции через реквизит.Как перенести аргумент index / id обратно в функцию deleteRecipe при нажатии кнопки?

//Recipes Component

class Recipes extends Component {
  constructor() {
    super();

    this.state = {
      recipes: [],
      input: ""
    };
  }

  componentDidMount() {
    axios
      .get("/api/recipes")
      .then(response => this.setState({ recipes: response.data }));
  }

  inputHandler = recipe => {
    this.setState({ input: recipe });
  };

  searchRecipe = () => {
    axios
      .get(`/api/recipes/label?label=${this.state.input}`)
      .then(response => this.setState({ recipes: response.data.hits }));
  };

  deleteRecipe = index => {
    let newRecipes = this.state.recipes;
    newRecipes.splice(index, 1);
    this.setState({ recipes: newRecipes });
  };

  render() {
    if (this.state.recipes) {
      var recipesDisplay = this.state.recipes.map((val, i) => {
        return (
          <Recipe
            key={val.recipe.id}
            id={val.recipe.id}
            name={val.recipe.label}
            img={val.recipe.image}
            url={val.recipe.url}
            cal={val.recipe.calories}
            ingredients={val.recipe.ingredientLines}
            deleteRecipe={this.deleteRecipe}
          />
        );
      });
    }

    return (
      <div>
        <Input changed={this.inputHandler} />
        <Button clicked={this.searchRecipe}>Search</Button>
        {recipesDisplay}
      </div>
    );
  }
}






//Recipe Component

const Recipe = props => {
  let newIngredients = props.ingredients.map((val, i) => {
    return <p key={i}>{val}</p>;
  });

  return (
    <div key={props.id} className="recipe">
      <div className="heading">
        <h1>{props.name}</h1>
        <Button>Edit</Button>
        <Button clicked={props.deleteRecipe}>Delete</Button>
      </div>
      <div className="info">
        <p>
          <strong>Calories:</strong> {props.cal.toFixed(0)}
        </p>
        <br />
        <p>
          <strong>Ingredients:</strong>
        </p>
        {newIngredients}
      </div>
      <a href={props.url} target="_blank">
        <img src={props.img} alt="food" />
      </a>
    </div>
  );
};






//Button Component

const Button = props => {
  return <button onClick={props.clicked}>{props.children}</button>;
};

1 Ответ

0 голосов
/ 09 июня 2018

Вы можете передать индекс компоненту рецепта, а затем, когда нажмете кнопку, передать его обратно с помощью функции deleteRecipe

class Recipes extends Component {
  constructor() {
    super();

    this.state = {
      recipes: [],
      input: ""
    };
  }

  componentDidMount() {
    axios
      .get("/api/recipes")
      .then(response => this.setState({ recipes: response.data }));
  }

  inputHandler = recipe => {
    this.setState({ input: recipe });
  };

  searchRecipe = () => {
    axios
      .get(`/api/recipes/label?label=${this.state.input}`)
      .then(response => this.setState({ recipes: response.data.hits }));
  };

  deleteRecipe = index => {
    let newRecipes = this.state.recipes;
    newRecipes.splice(index, 1);
    this.setState({ recipes: newRecipes });
  };

  render() {
    if (this.state.recipes) {
      var recipesDisplay = this.state.recipes.map((val, i) => {
        return (
          <Recipe
            key={val.recipe.id}
            id={val.recipe.id}
            index={i}
            name={val.recipe.label}
            img={val.recipe.image}
            url={val.recipe.url}
            cal={val.recipe.calories}
            ingredients={val.recipe.ingredientLines}
            deleteRecipe={this.deleteRecipe}
          />
        );
      });
    }

    return (
      <div>
        <Input changed={this.inputHandler} />
        <Button clicked={this.searchRecipe}>Search</Button>
        {recipesDisplay}
      </div>
    );
  }
}






//Recipe Component

class Recipe extends React.Component {
    deleteRecipe = () => {
       this.props.deleteRecipe(this.props.index);
    }
    render() {
      let newIngredients = this.props.ingredients.map((val, i) => {
        return <p key={i}>{val}</p>;
      });

      return (
        <div key={props.id} className="recipe">
          <div className="heading">
            <h1>{this.props.name}</h1>
            <Button>Edit</Button>
            <Button clicked={this.deleteRecipe}>Delete</Button>
          </div>
          <div className="info">
            <p>
              <strong>Calories:</strong> {this.props.cal.toFixed(0)}
            </p>
            <br />
            <p>
              <strong>Ingredients:</strong>
            </p>
            {newIngredients}
          </div>
          <a href={this.props.url} target="_blank">
            <img src={this.props.img} alt="food" />
          </a>
        </div>
      );
    }
}





//Button Component

const Button = props => {
  return <button onClick={props.clicked}>{props.children}</button>;
};
...