TypeError:无法在React中读取null的属性'label'

时间:2019-08-28 13:24:15

标签: reactjs

尝试通过将输入的value设置为''并清除错误TypeError: Cannot read property 'label' of null来清除输入

import React, { Component } from 'react'
import './add-item.sass'

export default class AddItem extends Component {
  state: {
    label: ''
  }

  onLabelChange = (event) => {
    this.setState({
      label: event.target.value
    })
  }

  onSubmit = (event) => {
    event.preventDefault()
    this.props.onItemAdded(this.state.label)
    this.setState({
      label: ''
    })
  }
  render() {
    return (
      <form className="add-item d-flex"
        onSubmit={this.onSubmit}>
        <input type="text"
          className="form-control add-item__input"
          onChange={this.onLabelChange}
          placeholder="new 2do"
          value={this.state.label}
        />
        <button
          className="btn btn-success"
          type="submit"
        >Add</button>
      </form>
    )
  }
}

2 个答案:

答案 0 :(得分:0)

请替换为:

state: { // By the way this needs to be  state=  not  state:
  label: ''
}

constructor () {
  super();

  this.state = {
    label: ''
  }
}

注意:在构造函数之外定义初始状态是一个不好的例子。

答案 1 :(得分:-1)

您也可以不使用构造函数。只需在状态前添加“ this”:

reduce