【问题标题】:React Todo list. form input not dissapearing after onsumbit反应待办事项列表。提交后表单输入不消失
【发布时间】:2018-09-02 09:39:01
【问题描述】:

对于我的生活,我不知道为什么我的 react 应用程序不起作用。我的输入状态在 onSubmit 之后呈现。但我的价值并没有在我的输入栏中消失。我的清单上没有任何内容。我只是在将我的组件分解成更小的块后才遇到这个问题,当它是 1 个完整的组件时,我可以毫无问题地完成这项工作。

class App extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      input: '',
      items: []
    }

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(e) {
    this.setState({
      input: e.target.value
    })
  }

  handleSubmit(e) {
    e.preventDefault();
    this.setState({
      input: '',
      items: [...this.state.items,this.state.input]
    })
    console.log(this.state.input)
  }

  render() {
    return (
      <div>
        <Form handleChange={this.handleChange} handleSubmit={this.handleSubmit}
        value={this.state.input}/>
        <List items={this.state.items}/>
      </div>
    )
  }
}

class Form extends React.Component {
  constructor(props){
    super(props)

  }

  render() {
    return (
      <form onSubmit={this.props.handleSubmit}>
        <input onChange={this.props.handleChange} value={this.props.input}/>
        <button>Submit</button>
      </form>
    )
  }
}

class List extends React.Component {
  render() {
    return (
      <ul>
        {
          this.props.items.map((item,index) => {
            <li key={index}>{item}</li>
          })
        }
      </ul>
    )
  }
}   

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    “不消失”的问题是因为:

    <input onChange={this.props.handleChange} value={this.props.input}/>
    

    没有任何input 属性,它是value。见:

    value={this.state.input}
    

    应该是这样的:

    <input onChange={this.props.handleChange} value={this.props.value}/>
    

    上市问题是因为这个:

    {
        this.props.items.map((item,index) => {
            <li key={index}>{item}</li>
        })
    }
    

    在这里,您使用的是箭头函数和主体块。如果使用正文块,则必须使用 return 语句。

    {
      this.props.items.map( ( item, index ) => {
        return ( <li key={index}>{item}</li> );
      } )
    }
    

    或者你可以像这样使用它:

    {
      this.props.items.map( ( item, index ) =>
        <li key={index}>{item}</li> )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 2018-06-24
      • 2019-05-05
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      • 2012-07-12
      相关资源
      最近更新 更多