如何在 React Hooks 中获取自定义属性的值?

How to get the value of custom atttributes in react hooks?

如何使用 React Hooks 获取自定义属性的值?

这是代码沙箱中的示例代码:demo live

代码

import "./styles.css";
import React, { useState } from "react";

export default function App() {
  const [value, setValue] = useState("");

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <select
        onChange={(e) => {
          console.log("value", e.target.value);
          console.log("description", e.target.description);
          setValue(e.target.value);
        }}
        name="cars"
        id="cars"
      >
        <option value="volvo" description="hahahahaa">
          Volvo
        </option>
        <option value="saab" description="hehehehehe">
          Saab
        </option>
        <option value="opel" description="hoooooooo">
          Opel
        </option>
        <option value="audi" description="huuuuuuuuuu">
          Audi
        </option>
      </select>
    </div>
  );
}

我可以获取属性值,但不能获取自定义描述。 我得到未定义 console.log("description", e.target.description);

这里有什么问题?

在您的示例中,target<select>,您需要遍历到所选选项并获取属性值。

当您可以使用以值作为键的哈希映射时,将数据存储在自定义选项属性中似乎确实不切实际

const Example = () => {
  const [desc, setDesc] = React.useState('')
  
  const descriptions = {
     volvo:'hahahahaa', 
      saab:'hehehehehe',
      opel:'hoooooooo'
  }
  
  const handleChange = (e)=>{
    const val =  e.target.value,
          des = descriptions[val]
     console.clear()
     console.log("value",val);
     console.log("description", des);
     setDesc(des)
  }

  return (
    <div>
    <div>Description: {desc}</div>
      <select
    onChange={handleChange}
    name="cars"
    id="cars"
  >
    <option value="volvo">
      Volvo
    </option>
    <option value="saab">
      Saab
    </option>
    <option value="opel" >
      Opel
    </option>  
  </select>
  
    </div>
  );
};

// Render it
ReactDOM.render(
  <Example title="Example using Hooks:" />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

e.target给你select标签,你可以得到选项标签和这样的描述:

console.log("description", e.target.childNodes[e.target.selectedIndex].getAttribute("description"));