简体   繁体   中英

How to prevent new line when enter is pressed in react-native

for a multiline textinput, when user press enter key, I want to achieve the goals:

  • keep textinput focus when user press enter key.
  • prevent add a new line.

i have't see any props what can do it, anyone has ideas?

react-native version is 0.28+, need supports ios and android.

In TextInput passing the props

blurOnSubmit = {true} and then in onBlur props focus the textInput field using ref,these two will prevents from entering a new line and the focus is retained on the text input field. If you want only to prevent the user from entering a newline blurOnSubmit = {true} is sufficient

The drawback here is you can see keyboard hides for a moment then pops up. Its bit like a hack. Hope someone can come up with another or improvise this

You can setup your TextInput with multiline and blurOnSubmit to false. This will keep the keyboard and allow multiline in the input.

And use the onKeyPress props only for sending a message.

onKeyPress({ nativeEvent: { key: keyValue } }) {
    if (keyValue === "Enter") this.sendMessage();
}

with

onMessageInputChange(message) {
    this.setState({
        message,
    });
}

This should work in both Android and iOS.

            <TextInput
                value={message}
                onChangeText={this.onMessageInputChange}
                onKeyPress={this.onKeyPress}
                returnKeyType="send"
                blurOnSubmit={false}
                multiline
            />

Here is example:

 $(".Post_Description_Text").keydown(function(e) { if (e.keyCode == 13 && !e.shiftKey) { e.preventDefault(); alert("New line entered"); } });
 .Post_Description_Text { width: 500px; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <textarea name="comment_text" id="comment_text" class="Post_Description_Text"></textarea>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM