首页 > 解决方案 > 如何将 function.bind(this) 转换为 react native 中的箭头函数?

问题描述

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

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

onChangeText我想写一个箭头函数并将formState.inputValues.title&text作为道具传递给textChangeHandler喜欢这个,

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

文本更改处理程序:

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,
    });
  };

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

标签: javascriptreactjsreact-nativethisarrow-functions

解决方案


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

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

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


推荐阅读