【问题标题】:Datalist return option's data-valueDatalist 返回选项的数据值
【发布时间】:2020-08-31 15:24:13
【问题描述】:

我希望有一个 onChange 函数,仅当在数据列表中选择一个选项时才返回“选项的数据值”。

那么我怎样才能返回作为所选选项隐藏值的数据值。

  const [country, setCountry] = useState();
  const [countries, setCountries] = useState([]);
  <input
    list="dropdown__countries"
    className="header__dropbtn"
    placeholder="Search Country"
    onChange={setCountry(event.target.value)}
  />
  <datalist id="dropdown__countries">
    {props.countries.map((country) => (
      <option data-value={country.value} value={country.name} />
    ))}
  </datalist>

这个 sn-p 中的 onChange 只返回输入数据。这不是我想要做的,我不想要输入数据,而是我想要(所选选项的数据值)

【问题讨论】:

    标签: javascript html reactjs


    【解决方案1】:

    您可以使用给定的当前value 找到country。

    function DataList(props) {
      const [countryValue, setCountryValue] = useState();
    
      function onChange(event) {
        const { value } = event.target;
    
        // find the country with the current selected value
        const country = props.countries.find((c) => c.name === value);
    
        if (country !== undefined) {
          // use selected country object here
    
          setCountryValue(country.value);
          console.log(country.value);
        }
      }
    
      return (
        <>
          <input
            list="dropdown__countries"
            className="header__dropbtn"
            placeholder="Search Country"
            onChange={onChange}
          />
          <datalist id="dropdown__countries">
            {props.countries.map((country) => (
              <option
                key={country.value}
                data-value={country.value}
                value={country.name}
              />
            ))}
          </datalist>
        </>
      );
    }
    

    【讨论】:

    • 感谢您的回复,非常感谢!但我编辑了我的问题,你能不能重读一下,也许不清楚
    • 谢谢老哥赞赏!!
    【解决方案2】:

    您错误地传递了 setCountry() 函数调用的值而不是函数。

    改为这样做:

     const [country, setCountry] = useState();
      const [countries, setCountries] = useState([]);
      <input
        list="dropdown__countries"
        className="header__dropbtn"
        placeholder="Search Country"
        onChange={(event)=>setCountry(event.target.value)}
      />
      <datalist id="dropdown__countries">
        {props.countries.map((country) => (
          <option data-value={country.value} value={country.name} />
        ))}
      </datalist>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-29
      • 2017-06-18
      • 2020-02-19
      • 1970-01-01
      • 1970-01-01
      • 2020-03-09
      • 2017-09-02
      • 1970-01-01
      相关资源
      最近更新 更多