使用Typescript的OnChange无效问题

时间:2019-07-11 12:15:15

标签: reactjs typescript

我在选择框上使用打字稿和onChange在React BoilerPlate上编写了代码,需要更新参数的状态。

我尝试了initialState传递数据onChange函数,下面是代码

export const initialState = {
  currencyRate: '',
  currencyCode: 'USD',
};

const changeCurrency = (state = initialState, args: any) => {
    produce(state, currency => {
      currency.currencyCode = args.target.value;
    });
    console.log(currencyCode);
  };

<select id="currency" name="currency" onChange={changeCurrency(
                { currencyRate: '', currencyCode: '' },
                null,
              )}
            >


我需要将值onchange设置为currencyCode状态

下面是错误

  

TS2322:类型'void'不可分配给类型'((event:   ChangeEvent)=> void)|未定义”

2 个答案:

答案 0 :(得分:1)

为解释问题,我们应正确设置代码格式:

export const initialState = {
  currencyRate: '',
  currencyCode: 'USD',
};

const changeCurrency = (state = initialState, args: any) => {
  produce(state, currency => {
    currency.currencyCode = args.target.value;
  });
  console.log(currencyCode);
};

return (
  <select
    id="currency"
    name="currency"
    onChange={changeCurrency({ currencyRate: '', currencyCode: '' }, null)}
  >

  </select>
);

如果您更接近传递onChanhe事件的方式,您会注意到,实际上不是在将函数传递给onChange而是将函数调用的结果传递给了它。让我们重写部分代码以更好地理解它:

const result = changeCurrency({ currencyRate: '', currencyCode: '' }, null);
return (
  <select
    id="currency"
    name="currency"
    onChange={result}
  >

  </select>
);

这正是您的代码所做的,我只是为函数调用的结果创建了一个变量。下一步是让您查看函数中实际返回的内容。答案是没有还是没有,这就是为什么您实际上要向onChange传递一个空白。如果您再次阅读错误消息,请考虑以下解释:

  

不能将类型'void'分配给类型'((event:ChangeEvent)=> void)|未定义”)

您会更好地理解它。

最简单的解决方法是像这样将函数传递给onChange:

return (
  <select
    id="currency"
    name="currency"
    onChange={(event) => {
      changeCurrency({ currencyRate: '', currencyCode: '' }, event)
    }}
  >

  </select>
);

答案 1 :(得分:0)

export const initialState = {
  currencyRate: '',
  currencyCode: 'USD',
};

// `const...` is equivalent to `function changeCurrency(event: ChangeEvent) {...}`
const changeCurrency = (state = initialState, args: any) => {
  // return a function with expected signature by onChange
  return (event: ChangeEvent): void => {
    produce(state, currency => {
      currency.currencyCode = args.target.value;
    });
    console.log(currencyCode);
  }
};
<select id="currency" name="currency" onChange={changeCurrency(
    { currencyRate: '', currencyCode: '' },
  null,
)}
>

Mehran Hatami的回答也是正确的,即使不是更可取的。