gpt4 book ai didi

javascript - react : Element is changing a controlled input of type text to be uncontrolled

转载 作者:行者123 更新时间:2023-11-28 13:09:41 26 4
gpt4 key购买 nike

我收到以下错误,但无法确定发生这种情况的原因

warning.js:36 警告:搜索框正在将文本类型的受控输入更改为不受控。输入元素不应从受控切换到不受控(反之亦然)。决定在组件的生命周期内使用受控或非受控输入元素

我有以下文件:

  1. 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 函数中。您已将输入的 onChange 事件命名为 e,但您正在从全局变量 event 获取值

onSearchChange 替换为下面提到的代码:

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

关于javascript - react : Element is changing a controlled input of type text to be uncontrolled,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43533521/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com