我收到以下错误,但无法确定发生原因

warning.js:36警告:Searchbox正在将文本类型的受控输入更改为不受控制。输入元素不应从受控状态切换到非受控状态(反之亦然)。确定在组件的使用寿命中使用受控或非受控输入元素

我有以下文件:


Searchbox.js




import React, { Component } from 'react';

    class Searchbox extends Component {

      // render method
      render() {
        const { value, onChange, onSubmit, children } = this.props
        console.log(value)
        console.log(onChange)
        console.log(onSubmit)
        console.log(children)
        return (
          <section className="search-section">
            <form onSubmit={onSubmit}>
              <input
                type="text"
                className="search-box"
                value={value}
                onChange={onChange}
              />
              <button type="submit">{children}</button>
            </form>
          </section>
        )
      }
    }

    export default Searchbox





和App.js文件



import React, { Component } from 'react';
import Searchbox from './components/Searchbox'
//import logo from './logo.svg';
import './App.css';

const DEFAULT_TERM = 'High Fidelity'

class App extends Component {

  // Constructor
  constructor(props) {
    super(props)

    this.state = {
      movie: null,
      searchTerm: DEFAULT_TERM
    }

    this.onSearchSubmit = this.onSearchSubmit.bind(this)
    this.onSearchChange = this.onSearchChange.bind(this)
  }


  // onSearchSubmit method
  onSearchSubmit(e) {
    e.preventDefault()
    console.log("Searching movie with name" + this.status.searchTerm)
  }

  onSearchChange(e){
    console.log(event.target.value)
    this.setState({ searchTerm: event.target.value })
  }

  // render method
  render() {

    const { movie, searchTerm } = this.state

    return (
      <div className="App">
        <Searchbox
          value={searchTerm}
          onChange={this.onSearchChange}
          onSubmit={this.onSearchSubmit}
        >Search
        </Searchbox>
      </div>
    );
  }
}

export default App;





加载时一切正常,但是当我在文本字段中键入内容时,就会触发错误。

有什么建议?

最佳答案

问题出在onSearchChange函数中。您已将input的onChange事件命名为e,但您正在从全局变量事件中获取价值

将onSearchChange替换为以下代码:

onSearchChange(event) {
   this.setState({ searchTerm: event.target.value })
}

10-02 19:05