【问题标题】:React Native : How to add multiple functions for onChangeText using FormikReact Native:如何使用 Formik 为 onChangeText 添加多个函数
【发布时间】:2022-08-22 22:11:54
【问题描述】:

我尝试制作一个简单的 TextInput 来限制用户可以使用 Formik 输入的单词数。

但是,我被困在这里.. 我使用 useSate 钩子来计算输入值的长度,这需要放入 TextInput 的 onChangeText 回调中。 同时,我还需要将用于提交内容的 handleChange(name) 放在 onChangeText 中.. 我意识到,只有其中一个可以使用下面的代码...... 我不知道发生了什么......你能看看我的代码吗?非常感谢您!

import { StyleSheet, Text, View,TextInput} from \'react-native\'
import React,{useState} from \'react\'
import { useFormikContext } from \'formik\';


const AppFormFieldWithCount = ({name,number,maxLength,minHeigh,multiline,placeholder,...otherProps}) => {
    const {setFieldTouched,handleChange,errors,touched} = useFormikContext();
    const[content,setContent] = useState(\'\');
  
  return (
   <>
    <View style={[styles.container,{height:minHeigh}]}>
   <TextInput placeholder={placeholder}
     style={{flex:1,fontSize:16}} 
     placeholder = {placeholder}
     multiline={multiline} 
     maxLength={maxLength}
     minHeigh ={minHeigh}
     onBlur = {()=>setFieldTouched(name)}
     onChangeText = { 
      (text) => {setContent(text);handleChange(name)}
     
    }
     {...otherProps}
      />
     <Text style={{position:\'absolute\',bottom:5,right:5,}}>{content === \"\" ? \"0\" : content.length}/{number}</Text>
     </View>

   </>
  )
}

export default AppFormFieldWithCount

const styles = StyleSheet.create({
  container:{
    flexDirection:\'row\',
    borderRadius:5,
    borderWidth:1,
    borderColor:\"black\",
    width:\'100%\',
    paddingHorizontal:10,
    marginVertical:10,

}
})

    标签: react-native formik textinput


    【解决方案1】:

    您可以使用来自useFormikContextsetFieldValue

    onChangeText = { 
      (text) => {
        setContent(text);
        setFieldValue('name', text)}
    }
    

    【讨论】:

      猜你喜欢
      • 2022-06-15
      • 1970-01-01
      • 2021-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 2019-04-07
      相关资源
      最近更新 更多