【问题标题】:Changing the placeholder of input in React在 React 中更改输入的占位符
【发布时间】:2021-06-15 03:21:43
【问题描述】:

我有 2 个搜索框。

<input type="text" class="main-input main-name"  placeholder="Search" /> 
<Select options={searchOptions} placeholder="Search by" isSearchable/>

第二个是选择组件,它允许用户通过两个选项之一选择搜索:名称或位置。 第一个输入是搜索框,用户将在其中根据 Select 中选择的选项输入特定名称或位置。我的目标是根据所选选项更改此输入的占位符。目前,占位符是搜索,但一旦用户选择名称,我希望占位符 =“键入名称”,或者如果选择的是位置,则分别显示“键入位置”。

const searchOptions = [
    {value: 'name', label:'Name'},
    {value: 'location', label:'Location'}
];

这些是提供给 Select 的选项。

为了存储选择的选项,我使用了 Usestate,为它创建了函数并更新了搜索框。这就是我的代码的样子:

function Searchbox () {
const [result,setResult]=useState(searchOptions.value)
const setResultHandler = e => {
  setResult(e.value);
}

 return (
     <input type="text" class="main-input main-name"  placeholder={{result}="name" ? "Type the Name" : "Type the Location"} />
      <Select options={searchOptions} onChange={setResultHandler} placeholder="Search by" isSearchable/>

这让我在更改占位符的地方出错 - TypeError: Assignment to constant variable。

当我尝试在搜索框下方添加 {result} 时,它可以工作,并且我可以看到所选选项的值,因此它可以正确存储该值,但它不适用于占位符。我不明白这是什么问题。

【问题讨论】:

    标签: reactjs input jsx react-select


    【解决方案1】:

    试试这样的:

         <input type="text" class="main-input main-name"  placeholder = {result === "name" ? "Type the Name" : "Type the Location"} />
    

    【讨论】:

    • 天啊,现在我犯了那个愚蠢的错误。该代码现在正在运行。非常感谢!
    猜你喜欢
    • 2013-11-22
    • 2021-05-08
    • 2018-02-09
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多