React-Native:使用自定义 TextInput 组件添加文本限制指示器
React-Native: Adding text limit Indicator with a custom TextInput component
我想要完成的是一个文本输入,它在自身的一侧显示类似 (0/255) 的文本。
组件的最少代码:
import React, { useState, useEffect} from 'react';
import { View, TextInput, Text } from 'react-native';
export default function InputWithIndicator({ Limit, ...otherProps }) {
const [charRemains, setCharRemains] = useState(0);
const [TextValues, setTextValues] = useState('');
const [TextLimit] = useState(Limit);
useEffect(() => {
setCharRemains(Limit-TextValues.length);
});
return (
<View >
<TextInput {...otherProps} onChangeText={value=>setTextValues(value)}/>
<Text>
{charRemains}/{TextLimit}
</Text>
</View>
);
}
在代码中放置组件:
<InputWithIndicator placeholder="Your name" maxLength={25} Limit={25} onChangeText={value=>setName(value)} />
它作为组件显示效果很好。但主要问题是 onChangeText 根本没有 return 任何值。
有什么办法吗?仅供参考,我也尝试过 onChange 事件。
使用onChange
代替onChangeText
看看我的样本:Sample
这是实时代码 https://snack.expo.dev/@raajnadar/text-input-with-length-limit。
<View style={styles.container}>
<TextInput
style={styles.input}
maxLength={TextLimit}
onChangeText={(value) => setText(value)}
/>
<Text>
{TextLimit - text.length}/{TextLimit}
</Text>
</View>
我想要完成的是一个文本输入,它在自身的一侧显示类似 (0/255) 的文本。
组件的最少代码:
import React, { useState, useEffect} from 'react';
import { View, TextInput, Text } from 'react-native';
export default function InputWithIndicator({ Limit, ...otherProps }) {
const [charRemains, setCharRemains] = useState(0);
const [TextValues, setTextValues] = useState('');
const [TextLimit] = useState(Limit);
useEffect(() => {
setCharRemains(Limit-TextValues.length);
});
return (
<View >
<TextInput {...otherProps} onChangeText={value=>setTextValues(value)}/>
<Text>
{charRemains}/{TextLimit}
</Text>
</View>
);
}
在代码中放置组件:
<InputWithIndicator placeholder="Your name" maxLength={25} Limit={25} onChangeText={value=>setName(value)} />
它作为组件显示效果很好。但主要问题是 onChangeText 根本没有 return 任何值。 有什么办法吗?仅供参考,我也尝试过 onChange 事件。
使用onChange
代替onChangeText
看看我的样本:Sample
这是实时代码 https://snack.expo.dev/@raajnadar/text-input-with-length-limit。
<View style={styles.container}>
<TextInput
style={styles.input}
maxLength={TextLimit}
onChangeText={(value) => setText(value)}
/>
<Text>
{TextLimit - text.length}/{TextLimit}
</Text>
</View>