简体   繁体   中英

Cannot access e.target.id even though its there when i log e.target in react

import { connect } from 'react-redux';
import { getClubs } from '../../actions/club';
import PropTypes from 'prop-types';

const ViewPlayers = ({ clubs, loading, getClubs }) => {
  useEffect(() => {
    getClubs();
  }, [getClubs]);

  const [form, editForm] = useState({
    club_id: ''
  });

  const selClub = e => {
    console.log(e.target); --> Has the id value set to the correct id
    console.log(e.target.id); --> outputs empty string
  };
  const submitData = e => {};
  return loading === true ? (
    <div>
      <h1>wait</h1>
    </div>
  ) : (
    <div className='container'>
      <h3>View players</h3>
      <form onSubmit={e => submitData(e)}>
        <div className='form-group'>
          <label className='mt-3'>
            <strong>Select Club</strong>
          </label>
          <select
            className='form-control mb-3'
            name='club'
            value={form.club_id}
            onChange={e => selClub(e)}
          >
            {clubs.map(data => {
              return (
                <option key={data._id} id={data._id}>
                  {data.name}
                </option>
              );
            })}
          </select>
        </div>
      </form>
    </div>
  );
};

ViewPlayers.propTypes = {
  loading: PropTypes.bool.isRequired,
  clubs: PropTypes.array.isRequired,
  getClubs: PropTypes.func.isRequired
};

const mapStateToProps = state => ({
  clubs: state.club.data,
  loading: state.club.loading
});

export default connect(mapStateToProps, { getClubs })(ViewPlayers);

Okay so i have set the id on option tag of the select statement to the id of the current club.. When i console.log(e.target) i can see the id value set for all the clubs in my data set.. But if i console.log(e.target.id) i get 'empty string' even though it is set on` the above console.log to the correct id???? if i do e.target.value i get the correct value also???

How is it not seeing the e,target.id???

Thanks in advance for any help

I don't know why you would even need to use the id attribute on option tags. You can specify an id for your select tag, at least it makes sense. For option tags what you want to do is specify their value attributes. Then you can access a selected value using e.target.value in your onChange handler.

<select
  className='form-control mb-3'
  name='club'
  value={form.club_id}
  onChange={e => selClub(e)}
>
  {clubs.map(data => {
    return (
      <option key={data._id} value={data._id}>
        {data.name}
      </option>
    );
  })}
</select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM