在JavaScript中向按钮添加功能?

时间:2018-12-28 21:25:17

标签: javascript reactjs jsx

在单击按钮时调用函数时遇到问题。 arrayMaker函数对搜索页面的结果进行排序。我希望单击排序按钮时在另一个component.js中触发该函数。我尝试使用<input type="button" onClick= myFunction/>以及onClick的许多变体(例如onClick= () => myFunctiononClick=myFunction()onClick={this.myFunction()}onClick={myFunction})。

到目前为止,我仅成功破解了该应用程序。有任何建议或指向要检出的资源的链接吗?

import React from 'react';
import axios from 'axios';
import {Grid} from 'semantic-ui-react';
import Search from './Search';
import DisplayRecipe from './Cards';
class Display extends React.Component {
  state = {
    recipes: [],
    ingredientName: '',
    fireRedirect: true,
    sortedRecipes: []
  }
  arrayMaker = (x) => {
    let newArray = [];
    for (let i = 0; i < x.length; i++) {
      let test = x[i]
      test.num_ingredients = test.ingredients.split(',').length;
      newArray.push(test)
    }
    let newTest = newArray.sort((a, b) => (a.num_ingredients - b.num_ingredients))
    console.log(newTest)
    this.setState({sortedRecipes: newTest})
  }
  handleSearchChange = e => {
    this.setState({ingredientName: e.target.value});
  };
  onSubmit = (e) => {
    e.preventDefault();
    axios.get(`http://cors-anywhere.herokuapp.com/recipepuppy.com/api/?i=${this.state.ingredientName}`).then((res) => {
      console.log(res.data.results);
      this.setState({recipes: res.data.results, fireRedirect: false})
      // console.log(this.state.recipes[0].ingredients.split(',').length)
      let test = this.arrayMaker(this.state.recipes)
      // let newTest = test.sort((a, b) => b - a)
      console.log(test)
      // console.log(this.state.recipes.arrayMaker());
    });
  };
  render() {
    return (<div>
      {this.state.fireRedirect && <Search handleSearchChange={this.handleSearchChange} ingredientValue={this.state.ingredientName} onSubmit={this.onSubmit}/>}
      <Grid className="background" columns='equal' centered="centered">
        {
          this.state.sortedRecipes.map((recipe, index) => {
            return <DisplayRecipe key={index} recipe={recipe}/>
          })
        }
      </Grid>
    </div>);
  }
}
export default Display;

1 个答案:

答案 0 :(得分:0)

当代码中没有按钮时,非常难。通常这就是我在react中实现按钮的方式

import React from 'react';
import axios from 'axios';
import {Grid} from 'semantic-ui-react';
import Search from './Search';
import DisplayRecipe from './Cards';
class Display extends React.Component {
  state = {
    recipes: [],
    ingredientName: '',
    fireRedirect: true,
    sortedRecipes: []
  }
  doTheThing = (e) => {
    console.log(`we have the event ${e}`)
    e.preventDefault()
  }
  arrayMaker = (x) => {
    let newArray = [];
    for (let i = 0; i < x.length; i++) {
      let test = x[i]
      test.num_ingredients = test.ingredients.split(',').length;
      newArray.push(test)
    }
    let newTest = newArray.sort((a, b) => (a.num_ingredients - b.num_ingredients))
    console.log(newTest)
    this.setState({sortedRecipes: newTest})
  }
  handleSearchChange = e => {
    this.setState({ingredientName: e.target.value});
  };
  onSubmit = (e) => {
    e.preventDefault();
    axios.get(`http://cors-anywhere.herokuapp.com/recipepuppy.com/api/?i=${this.state.ingredientName}`).then((res) => {
      console.log(res.data.results);
      this.setState({recipes: res.data.results, fireRedirect: false})
      // console.log(this.state.recipes[0].ingredients.split(',').length)
      let test = this.arrayMaker(this.state.recipes)
      // let newTest = test.sort((a, b) => b - a)
      console.log(test)
      // console.log(this.state.recipes.arrayMaker());
    });
  };
  render() {
    return (<div>
      {this.state.fireRedirect && <Search handleSearchChange={this.handleSearchChange} ingredientValue={this.state.ingredientName} onSubmit={this.onSubmit}/>}
      <Grid className="background" columns='equal' centered="centered">
        {
          this.state.sortedRecipes.map((recipe, index) => {
            return <DisplayRecipe key={index} recipe={recipe}/>
          })
        }
      </Grid>
      <button
        onClick={
          (e) => this.doTheThing(e)
      }/>
    </div>);
  }
}
export default Display;