使用React JS进行下拉的OnChange事件

var MySelect = React.createClass({
     change: function(){
         return document.querySelector('#lang').value;
     },
     render: function(){
        return(
           <div>
               <select id="lang">
                  <option value="select" onChange={this.change}>Select</option>
                  <option value="Java" onChange={this.change}>Java</option>
                  <option value="C++" onChange={this.change}>C++</option>
               </select>
               <p></p>
               <p value={this.change}></p>
           </div>
        );
     }
});

React.render(<MySelect />, document.body);

onChange事件不起作用。

小卤蛋Near小卤蛋2020/03/11 14:53:56

React Hooks (16.8+):

const Dropdown = ({
  options
}) => {
  const [selectedOption, setSelectedOption] = useState(options[0].value);
  return (
      <select
        value={selectedOption}
        onChange={e => setSelectedOption(e.target.value)}>
        {options.map(o => (
          <option value={o.value}>{o.label}</option>
        ))}
      </select>
  );
};