如何在React中将带有参数的方法传递给子级? (无法读取未定义的属性“ props”)

时间:2019-05-07 08:32:29

标签: reactjs

我当前正在做一个待办事项清单,但不幸的是遇到了一些错误,导致我无法将方法传递给子组件。

const React = require('react');
class App extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      items: [],
      input: ""
    }
    this.inputChange = this.inputChange.bind(this);
    this.addItems = this.addItems.bind(this);
    this.remItems = this.remItems.bind(this);   
  }
  inputChange(event){
    this.setState({
      input: event.target.value
    })
  }

  addItems(){
    event.preventDefault()
    const temp = this.state.input 
    this.setState({
      input: "",
      items: this.state.items.concat(temp)
    })
  }
  remItems(id){
    const temp = [...this.state.items]
    const updatedItems = temp.filter(item => item.id!==id)
    this.setState({
      items: updatedItems
    })
  }
  render(){
  return (
    <div class = "w-100 p-3">
        <p>Enter your item here:</p>
       <form onSubmit = {this.addItems} class="form.inline">  
          <input class = "form.control mb-2 mr-sm-2" value = {this.state.input} onChange = {this.inputChange}/>
          <button type="submit" class="btn btn-primary mb-2">Add</button>
      </form>
      <UnorderedList items={this.state.items} remove = {this.remItems}/>
    </div>
  );
  }
}

class UnorderedList extends React.Component {
  constructor(props){
    super(props)
  }
  render(){
  return (
    <ul>
      {this.props.items.map(function(item, i) {
        return (<div id = "entry" class = "d-flex">
            <li key={i}>{item}</li>
            {console.log(i)}
            <button class = 'btn btn-sm btn-primary ml-auto' onClick = {() => this.remItems}> Done! </button>
          </div>)
      })}
    </ul>
    )
  }
}

我希望能够通过id键删除项目,但是它给我“无法读取未定义的属性'props'”。感谢您的帮助!

0 个答案:

没有答案