【发布时间】:2021-05-13 22:16:06
【问题描述】:
我正在使用 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 Chocolate,写在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>
)
}
}
有没有办法改变占位符的值?尽管占位符值不同,但我真的不知道为什么它会停留在该特定值。
编辑:为 TextInput 组件添加了 text.js 的代码
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
【问题讨论】:
-
可以分享
TextInput组件的代码吗? -
当然 @EmanueleScarabattoli 我已经添加了它
-
如果您在代码中全局搜索
Search Instagram(在 vscode 中为 Ctrl +Shift + F),此文本是否存在于代码中的任何位置?还可以尝试重新启动本地开发服务器,以确保本地更改反映在 UI 上 -
还要检查 CSS 类
search,因为通过一些技巧,也可以使用 CSS 设置占位符。 -
哇。非常感谢@KaranGarg 它在 bundle.js 和一些快照文件中。非常感谢。我真的很想做一些像全局搜索这样的功能,但我不知道该怎么做。现在,我学会了。非常感谢。
标签: reactjs placeholder textinput