【发布时间】: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