首页 > 解决方案 > React TextInput 占位符停留在特定值

问题描述

我正在使用 React JS 进行社交媒体克隆。但我无法更改占位符值。这是我文件search.js中用于呈现搜索框的代码,如下所示

<div className="search_box">
 <TextInput
  placeholder="Search Chocolate"
  autoFocus
  value={value}
  valueChange={this.search}
  className="search"
 />
 <span className="search_icon">
  <FAIcon icon="search" />
 </span>
</div>

这是搜索框的代码: 在此处输入图像描述

如您所见,即使占位符显示Chocolate,它也会呈现为Instagram 另外,可以肯定的是,我使用 chrome 中的 react dev 工具来检查哪个呈现这个组件,它还说search.js那个呈现搜索组件

在此处输入图像描述

因此,开发工具中的占位符甚至说占位符是Search Instagram,尽管它显然是用.search.js

我的完整代码search.js如下

import React, { Component } from 'react'
import { post } from 'axios'
import MapSearch from './map-search/map-search'
import FAIcon from '../icons/font-awesome-icon'
import TextInput from '../input/text'

export default class Search extends Component {
  state = {
    value: '',
    search: {
      users: [],
      groups: [],
      hashtags: [],
    },
  }

  hide = () => {
    this.setState({
      search: {
        users: [],
        groups: [],
        hashtags: [],
      },
    })
  }

  search = async ({ target: { value } }) => {
    this.setState({ value })
    if (value.trim() != '') {
      let { data } = await post('/api/search-instagram', { value })
      this.setState({ search: data })
    } else {
      this.hide()
    }
  }

  clicked = () => {
    this.setState({ value: '' })
    this.hide()
  }

  render() {
    let {
      value,
      search: { users, groups, hashtags },
    } = this.state

    return (
      <div>
        <div className="search_box">
          <TextInput
            placeholder="Search Chocolate"
            autoFocus
            value={value}
            valueChange={this.search}
            className="search"
          />
          <span className="search_icon">
            <FAIcon icon="search" />
          </span>
        </div>

        {users.length > 0 || groups.length > 0 || hashtags.length > 0 ? (
          <MapSearch
            users={users}
            groups={groups}
            hashtags={hashtags}
            clicked={this.clicked}
          />
        ) : null}
      </div>
    )
  }
}

反正有没有改变占位符的值?尽管占位符值不同,但我真的不知道为什么它会停留在该特定值上。

text.js编辑:为TextInput组件添加代码

import React from 'react'
import { string, func, oneOf, bool } from 'prop-types'

const TextInput = ({ type, placeholder, value, valueChange, ...props }) => (
  <input
    type={type}
    placeholder={placeholder}
    spellCheck="false"
    autoComplete="false"
    value={value}
    onChange={valueChange}
    {...props}
  />
)

TextInput.defaultProps = {
  type: 'text',
  placeholder: '',
  value: '',
  maxLength: '255',
  disabled: false,
}

TextInput.propTypes = {
  type: oneOf(['text', 'email', 'password']),
  placeholder: string.isRequired,
  value: string.isRequired,
  valueChange: func.isRequired,
  maxLength: string,
  disabled: bool,
}

export default TextInput

标签: reactjsplaceholdertextinput

解决方案


发送目标值。就像是: valueChange={(e)=> this.search(e.target.value)}


推荐阅读