【问题标题】:How can I convert function.bind(this) to an arrow function in react native?如何将 function.bind(this) 转换为 react native 中的箭头函数?
【发布时间】:2021-06-16 16:19:30
【问题描述】:

我想将我的函数转换为箭头函数,但每当我传递道具时,它都会给我未定义的错误。

<TextInput
            style={styles.input}
            value={formState.inputValues.title}
            onChangeText={textChangeHandler.bind(this, "title")}
          />

onChangeText 中,我想写一个箭头函数并将formState.inputValues.titletext 作为道具传递给textChangeHandler,就像这样,

<TextInput
            style={styles.input}
            value={formState.inputValues.title}
            onChangeText={(formState.inputValues.title, text) => {
              textChangeHandler(formState.inputValues.title, text);
            }}
          />

textChangeHandler:

const textChangeHandler = (inputIdentifier, text) => {
    let isValid = false;
    if (text.trim().length > 0) {
      isValid = true;
    }
    dispatchFormState({
      type: FORM_INPUT_UPDATE,
      value: text,
      isValid: isValid,
      input: inputIdentifier,
    });
  };

但我收到未定义的错误。我觉得我做错了,我该怎么做?

【问题讨论】:

  • 什么是未定义的?另外,对于你来说,两种情况下 textChangeHandler 的定义是否相同(箭头和非箭头)?
  • @TusharShahi 如果我按照上面的说明进行操作,则会出现语法错误,如果我只传递文本,则 textInput 字段无法正常工作。另外,如果在onChangeText 中没有传递任何内容,则显示错误Can't find variable: text
  • 首先你的函数需要两个参数。当您使用绑定时,它只会得到一个。
  • @TusharShahi 函数与 bind 工作正常。但我想将其转换为箭头函数。所以这就是我要问的我该怎么做?
  • 在你的箭头函数中试试这个,让我们知道会发生什么 textChangeHandler(text);

标签: javascript reactjs react-native this arrow-functions


【解决方案1】:

问题是 onChangeText 只接受一个参数来改变值 check out react-native Docs 此外,您不需要传递您的状态,因为您始终可以访问它。 以下或其中一些应该可以工作

onChangeText={(text) => {
   textChangeHandler(formState.inputValues.title, text);
}}

你不是在调用函数只是内联创建它。它需要匹配它正在使用的道具的签名。

【讨论】:

  • 我已经试过了。这是行不通的。 TextInput 工作不正常。每当我尝试添加某些内容时,它都会自动删除它。
  • @HarshMishra 你遇到错误了吗?能不能加个沙箱完整代码?
  • 不,我没有收到任何错误但我也无法在TextInput 中写入,因为它会自动删除。
  • 我不知道你的状态对象是什么样的,但value={formState.inputValues.title}应该是value={formState.inputValues.value}
猜你喜欢
  • 2020-03-07
  • 1970-01-01
  • 1970-01-01
  • 2022-12-06
  • 1970-01-01
  • 2019-04-12
  • 2020-05-07
  • 2021-12-13
相关资源
最近更新 更多