【发布时间】:2019-02-19 21:16:24
【问题描述】:
如何在 react native 的 TextInput 中实现 @mention?
我已经尝试过这个react-native-mention,但它不再被维护了。有很多样式问题和回调问题。
我想要的是在 TextInput 中显示自定义视图。像这样的。
点击列表后,我想显示如下:
到目前为止,我能够实现:
当我在 TextInput 中输入“@”时出现用户列表。
当我点击用户时,我会在 TextInput 中获得用户名
代码:
renderSuggestionsRow() {
return this.props.stackUsers.map((item, index) => {
return (
<TouchableOpacity key={`index-${index}`} onPress={() => this.onSuggestionTap(item.label)}>
<View style={styles.suggestionsRowContainer}>
<View style={styles.userIconBox}>
<Text style={styles.usernameInitials}>{!!item.label && item.label.substring(0, 2).toUpperCase()}</Text>
</View>
<View style={styles.userDetailsBox}>
<Text style={styles.displayNameText}>{item.label}</Text>
<Text style={styles.usernameText}>@{item.label}</Text>
</View>
</View>
</TouchableOpacity>
)
});
}
onSuggestionTap(username) {
this.setState({
comment: this.state.comment.slice(0, this.state.comment.indexOf('@')) + '#'+username,
active: false
});
}
handleChatText(value) {
if(value.includes('@')) {
if(value.match(/@/g).length > 0) {
this.setState({active: true});
}
} else {
this.setState({active: false});
}
this.setState({comment: value});
}
render() {
const {comments} = this.state;
return (
<View style={styles.container}>
{
this.state.active ?
<View style={{ marginLeft: 20}}>
{this.renderSuggestionsRow()}
</View> : null
}
<View style={{ height: 55}}/>
<View style={styles.inputContainer}>
<TextInput
style={styles.inputChat}
onChangeText={(value) => this.handleChatText(value)}
>
{comment}
</TextInput>
<TouchableOpacity style={styles.inputIcon} onPress={() => this.addComment()}>
<Icon type='FontAwesome' name='send-o' style={{fontSize: 16, color: '#FFF'}}/>
</TouchableOpacity>
</View>
</View>
);
}
【问题讨论】:
-
您将需要一个
Animated.View,使用绝对定位将其置于文本框内或下方,然后在 TextInput 上的onKeyPress函数中检查按下的键是否为@ -
@RobbieMilejczak 我能够实现你想说的......现在我的问题是如何在 TextInput 中显示
-
你找到解决办法了吗?
-
一种解决方案是使用github.com/taskrabbit/react-native-parsed-text 这样您就可以实现
@username呈现粗体并且用户可以按下它(您可以使用正则表达式检测@username图案)。这已经足够了,还是您真的需要在文本中显示自定义视图?
标签: react-native textinput mention