【问题标题】:React native text input synthetic event issue反应本机文本输入合成事件问题
【发布时间】:2023-02-19 19:46:57
【问题描述】:

我在 React Native 中制作了一个可重用的文本输入组件,但是当我尝试访问文本值时,它为我提供了合成事件对象,然后是文本值,我无法定位文本值。我知道这可能是重复的,但我尝试了很多方法但它不起作用。这是我的代码 sn-p。

/**Imported Component **/

<InputField
     placeholder="Disabilities"
     defaultValue={values.associatedDisabilities.toString()}
     onChange={(value) => console.log(value)}
/>

/**Reusable Component **/

<TextInput
          style={[
            styles.textInput,
            props.style,
            { color: theme.colors.mainForeground },
          ]}
          onChangeText={props.onChange}
          defaultValue = {props.defaultValue}
          value={props.value}
          onBlur={props.onBlur}
          {...props}
          placeholderTextColor={
            currentTheme === ThemeTypes.LIGHT
              ? theme.colors.secondaryText
              : theme.colors.mainForeground
          }
          editable={props.editable}
          selectTextOnFocus={props.editable}
/>

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    您需要将其传递给 onChange 才能获得所需的值:

    <TextInput
              style={[
                styles.textInput,
                props.style,
                { color: theme.colors.mainForeground },
              ]}
              onChangeText={(value) => props.onChange(value)}
              defaultValue = {props.defaultValue}
              value={props.value}
              onBlur={props.onBlur}
              {...props}
              placeholderTextColor={
                currentTheme === ThemeTypes.LIGHT
                  ? theme.colors.secondaryText
                  : theme.colors.mainForeground
              }
              editable={props.editable}
              selectTextOnFocus={props.editable}
    />
    

    其次,您需要控制导入的 comp:

    <InputField
         placeholder="Disabilities"
         defaultValue={values.associatedDisabilities.toString()}
         onChange={(value) => console.log(value)}
         value
    />
    

    否则你可以使用event.target.value,这是输入组件的原生事件值

    【讨论】:

    • 他们都给出了相同的合成事件对象
    • 你能添加一个有效的 sn-p 吗?
    【解决方案2】:

    onChange 是 TextInput 的内部事件,尝试将其更改为其他道具,如 updateValue={(val) => console.log(val)}

    <InputField
     placeholder="Disabilities"
     defaultValue={values.associatedDisabilities.toString()}
     // onChange={(value) => console.log(value)}
     updateValue={(value) => console.log(value)}
     />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      • 2020-03-20
      • 1970-01-01
      • 1970-01-01
      • 2016-11-10
      • 2019-10-10
      相关资源
      最近更新 更多