在 JSX 中使用 select 控件从未触发 onchange 事件

Onchange event never triggered using select control in JSX

我正在使用 React 尝试在功能组件中使用 Select 控件触发 onChange 事件。问题是当我 select 任何可用选项时,永远不会触发 onChange 侦听器方法,这是我的代码:

import React, { useState } from 'react';
import './ExpensesFilter.css';

const ExpensesFilter = (props) => {
  const [year, setYear] = useState('');

  const yearChangeHandler = (event) => {
    /* setYear actualiza, por medio de useState, 
    a year de manera asincrona, useState es un hooks
     */
    setYear(event);
    console.log("the user is filtering by year");
    console.log("year selected: "+year);
  };

    return (
        <div className='expenses-filter'>
          <div className='expenses-filter__control'>
            <label>Filter by year</label>
            <select onChange={yearChangeHandler}>
              <option value='2022'>2022</option>
              <option value='2021'>2021</option>
              <option value='2020'>2020</option>
              <option value='2019'>2019</option>
            </select>
          </div>
        </div>
      );
}

export default ExpensesFilter;

这个组件是这样实现的:

import React, { useState } from 'react';
import './Expenses.css';
import ExpenseItemV3 from './ExpenseItemV3';
import Card from '../UI/Card';
import ExpenseFilter from './NewExpense/ExpensesFilter';

const Expenses = (props) => {

    return (
        <div>
            <Card className="expenses">
                <div>
                    <ExpenseFilter />
                    <ExpenseItemV3
                        title={props.records[0].title}
                        amount={props.records[0].amount}
                        date={props.records[0].date}>
                    </ExpenseItemV3>
                </div>
                ...

到目前为止我没有想法,非常感谢您的意见,非常感谢

要设置 selected 选项的值,您必须达到事件目标值并将值设置为 select 标记,如下所示:

setYear(event.target.value);
<select value={year} onChange={yearChangeHandler}>

只需在 select 标签中添加 value={year},然后在 onChange 方法中,将年份设置为 event.target.value。 此外,year 的日志语句应该在 onChange 处理程序之外。适合我。