【问题标题】:Can't type in my input since i've set its value to this.state in ReactJS无法输入我的输入,因为我已在 ReactJS 中将其值设置为 this.state
【发布时间】:2017-10-07 13:33:31
【问题描述】:

我面临一些基本的 React 问题。

我使用更改处理和 onKeyPress 处理进行了基本文本输入,但由于我将其值设置为 this.state.currentSearchText,我无法输入它,所有内容都已绑定,并且它正在处理其他一些项目。我需要光。

我的意见:

<input type="text" value={this.state.currentSearchText} className="search-header input-text" placeholder={searchInputPlaceholder} onChange={this.handleChange} onKeyPress={(e) => this.handleKeyPress(e)} autoComplete="off"/>

我的变更处理函数:

handleChange(event) {

        this.setState({currentSearchText: event.target.value})

                console.log(this.state.currentSearchText)

        event.target.value.length === 0 ? this.displayHistory() : this.displaySearch()

                this.timeoutGTM = setTimeout(() => {
                    pushGTM({
                        searchTerm: this.state.currentSearchText,
                        event: 'search_event'
                    })
                }, 400)

}

我的按键处理:

handleKeyPress(event) {
          if (event.key === 'Enter' && this.state.currentSearchText.length > 0) {
            this.context.router.push('/search?searchEntry=' + this.state.currentSearchText)
          }
        }

我的 SearchBar 组件的状态:

class SearchBar extends Component {
    constructor(props) {
        super(props)

        this.state = {
            currentSearchText: '',
            resultsPosition: 0,
            nbTotalResults: 0,
            nbHistoryItems: 0,
            viewMode: false,
            lastKeyPressed: '',
            showResultsThumbnail: false
        }

        this._handleKeyPress = this._handleKeyPress.bind(this)
        this.handleChange = this.handleChange.bind(this)
        this.handleKeyPress = this.handleKeyPress.bind(this)
        this.hideSearchContent = this.hideSearchContent.bind(this)

        ControllerShortcuts.setOnKeyboardKeyPress('/', () => {
            this._refInputSearch.focus()
            this.onFocus()
        })
    }

【问题讨论】:

  • handleChange函数中的console.log(event.target.value)是否记录输入的值
  • 它确实记录了一个空格..
  • 阅读文档... setState 不会立即设置状态。如果您依赖已设置的状态,请使用它的回调参数...
  • facebook.github.io/react/docs/forms.html#controlled-components 这告诉我完全按照我的方式去做。
  • this.timeoutGTM = setTimeout(() =&gt; { pushGTM({ searchTerm: this.state.currentSearchText, event: 'search_event' }) }, 400) 在这里做什么。我认为问题出在那儿,因为如果我删除它并同时使用我们的代码,它似乎可以正常工作

标签: javascript reactjs input binding


【解决方案1】:

在您的输入字段中仅使用 onChange

<input type="text" value={this.state.currentSearchText} className="search-header input-text" placeholder={searchInputPlaceholder} onChange={this.handleChange} autoComplete="off"/>

【讨论】:

    猜你喜欢
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 2019-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多