javascript - React子组件props : _this2. props.delete它不是一个函数

标签 javascript reactjs function

我想听听您对我尝试创建食谱盒的见解。

https://codepen.io/gianndall/pen/evyBYd?editors=0010

class RecipeList extends React.Component {

  constructor(props) {
    super(props); 
    this.state = {
    }
  }

  render() { 
        var list = JSON.parse(this.props.recipes);
  console.log (list);
    return (      
      <ul className="collection">
        {list.map( (x) => 
                  <li className="collection-item">
                    <div>
                      {x.name} {list.indexOf(x)}                      
                      <a href="#!" className="secondary-content">
                        <i className="material-icons"
                          onClick = {() => this.props.deleteIt(list.indexOf(x))}
                          >delete</i></a>
                      <a href="#!" className="secondary-content"><i className="material-icons">edit</i></a>
                    </div>
                  </li> )}
      </ul>
    )
  }
}

class AddRecipeModal extends React.Component {

    constructor(props) {
    super(props);
    this.state = {
      input1: '',
      textarea1: ''
    }
  }    

  handleChangeTextarea(event) {
    this.setState({textarea1: event.target.value});
  }
  handleChangeInput(event) {
    this.setState({input1: event.target.value});
  }

  handleSubmit(event) {
    alert('A recipe was submitted: ' + this.state.input1 + ' '+ this.state.textarea1);
    event.preventDefault();
     if(typeof(Storage) !== "undefined") {

    console.log(localStorage.Recipes);

    if (localStorage.Recipes){

      var newRecipe = this.state.input1;
      var newIngredient = this.state.textarea1.split(',');
      console.log( 'vers 2' , newRecipe);
      var x = JSON.parse( localStorage.Recipes );
      console.log('vers 2' , x);
      x.push(
        {name:newRecipe,
         contans: newIngredient
        }
      );
      var updated = localStorage
      .setItem('Recipes',JSON.stringify(x));

    }else{
      var i=[];
      var newRecipe = this.state.input1;
      var newIngredient = this.state.textarea1.split(',');
      i.push(
        {name:newRecipe,
         contans: newIngredient
        }
      );
      localStorage
      .setItem('Recipes',JSON.stringify(i));
      console.log('vers 1 i= ',i);
      console.log('vers1 RECIPES ', localStorage.Recipes);      
    }

  }else{
        alert("Sorry, your browser does not support web storage...");
    }
  console.log('test');
    {this.props.closeIt()}
  }

  render() {
    return(

    <div id="modal1" className= {'modal ' + (this.props.display ? 'open' : '') }>
        <div className="modal-content">
          <h4>Add Recipe</h4>
          <form onSubmit={this.handleSubmit.bind(this)} >
          <div className="input-field" >
            <input id="input1" type="text" value={this.state.input1} onChange={this.handleChangeInput.bind(this)} />
            <label for="first_name">Recipe Name</label>
          </div>

          <div className="input-field" >
          <textarea id="textarea1" className="materialize-textarea" value={this.state.textarea1} onChange={this.handleChangeTextarea.bind(this)} />
          <label for="textarea1">Ingredient - separate with comma:</label>
          </div>
            <button type="Submit" className="waves-effect waves-light btn"><i className="material-icons left">add</i>Add it</button>
          </form>
        </div>
        <div className="modal-footer">
          <a href="#!" className="modal-action modal-close waves-effect waves-green btn-flat" onClick={this.props.closeIt}>Cancel</a>
        </div>
      </div>
      )
  }

}

class RecipesBox extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      modalShow: false
    }
  }  

  openModal(){
    this.setState({
      modalShow: true
    })
  }

  closeModal(){
    this.setState({
      modalShow: false
    })
  }

  deleteRecipe(x) {
    console.log('test', x);
    var list = JSON.parse(localStorage.Recipes);
    list.splice(x,1);
    console.log('list =',list);
    localStorage.Recipes = JSON.stringify(list);
  };


  render() {

    const listed = localStorage.Recipes ?
        <RecipeList recipes={localStorage.Recipes} deletIt={this.deleteRecipe}/> :
        <ul className="collection"><li className="collection-item">The Recipe Box is empty</li>
      </ul> 

      return (      
      <div>
        <nav className="nav-extended">
          <div className="nav-content">
            <span className="nav-title">Recipe Box</span>
            <a className="btn-floating btn-large halfway-fab waves-effect waves-light teal" onClick={this.openModal.bind(this)}>
              <i className="material-icons">add</i>
            </a>
          </div>
        </nav>
        {listed}
        < AddRecipeModal display={this.state.modalShow} closeIt ={this.closeModal.bind(this)}/>


   </div>      
    )    
  }
}

class newRecipe extends React.Component {}

ReactDOM.render(
  < RecipesBox />,
  document.getElementById('app')
);

经过几天的阅读和沮丧,我无法删除列表项。我在创建带有参数的 props 函数时遇到问题,该函数将值从子级传递到父级(特别是本地存储数组索引)。

我不断收到 _this2.props.deleteIt is not a function 错误

当然,我可以创建一个巨大的组件并使我的生活更轻松,但这不是重点。我想学习如何处理较小的组件

我真的希望你能对此提供一个新的视角。

谢谢

最佳答案

您必须将其作为 deleteIt 传入,而不是 deletIt:

<RecipeList deletIt={this.deleteRecipe} />

应该是

<RecipeList deleteIt={this.deleteRecipe} />

此外,将来您可能需要在 deleteRecipe 方法中引用 this。因此,此时您可能需要使用箭头函数或 .bind

关于javascript - React子组件props : _this2. props.delete它不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47550929/

相关文章:

javascript - JavaFX 容器内的 Java、JavaFx : Inserting a HTML&JS(static, 无互联网)项目

javascript - 使用 controllerAs 时访问指令中的父范围

c# - 如何将 DotNet Core 5.0 身份验证与 Next.js 结合使用

javascript - 将 Runtime 更改为 Node.js 10 后云功能失败

javascript - 类型中缺少属性 'children'

javascript - 如何禁用 redux-form 中的字段?

jquery - 使点击事件之外的 jQuery 变量可供其他函数使用

c++ - 未定义模板的隐式实例化 'class'

java 函数 - 打印(集合 c)?

javascript - 浏览器通过 Angular 路由在 SPA 内触发重新加载