React HTML select element onChange function, trying to access 'event.target.value'

后端 未结 2 695
花落未央
花落未央 2021-01-28 19:05

When using a controlled HTML

提交评论

  • 2021-01-28 19:28

    As correct as ravibagul91 is, I think you are taking a convoluted route to do a relatively simple thing and you aren't really taking advantage of how state actually works.

    First, are you getting anything out of having propB in the same state object as propA? From the code, it doesn't seem like it and it's not a bad idea to manage propA and propB in separate states.

    That said, you can call the set method for a state directly from the select because it doesn't appear like you need to know anything about the previous state.

    function App() {
    
      const [propA,setPropA] = React.useState('');
      const [propB,setPropB] = React.useState('');
    
      return(
        <React.Fragment>
          <div>Prop A: {propA}</div>
          <div>Prop B: {propB}</div>
          <select 
            value={propA} 
            onChange={e => setPropA(e.target.value)}
          >
            <option value='foo1'>foo1</option>
            <option value='foo2'>foo2</option>
            <option value='foo3'>foo3</option>
          </select>
        </React.Fragment>
      );
    }
    
    ReactDOM.render(<App/>, document.getElementById('root'));
    

    Much easier to read, understand, and maintain IMO.

    0 讨论(0)
  • 提交回复
    热议问题