简体   繁体   English

在 React Native 中每次按键时键盘都会消失

[英]Keyboard disappears on every key press in React Native

I want to map key value pairs in react native.我想在 react native 中映射键值对。 The value being editable text entry.该值是可编辑的文本条目。 The mapped components show up fine, but when I try to edit the TextInput, the keyboard disappears when i type the first letter.映射的组件显示正常,但是当我尝试编辑 TextInput 时,当我输入第一个字母时键盘消失了。 Don't know whats causing the problem.不知道是什么原因造成的问题。

If i just put a TextInput in the parent element, it works absolutely fine but doesn't work when I use the map function.如果我只是在父元素中放置一个 TextInput,它工作得很好,但在我使用 map 函数时不起作用。

 <View style={styles.main}>
        <View>
            {this._getDetailElements()}
        </View>
 </View>

_getDetailElements() function _getDetailElements() 函数

 _getDetailElements = () => {

    return Object.keys(this.state.data).map(elem => (
        <View key={shortid.generate()} style={styles.element}>
                <TextInput
                editable={this.state.editable}
                onChangeText={text => this.setState({seletedText: text})}
                value={this.state.selectedText}
                /> 
        </View>
    )
    );
}

i think you should just change the value to defaultValue Like this :我认为您应该将value更改为defaultValue像这样:

    <TextInput
        editable={this.state.editable}
        onChangeText={text => this.setState({seletedText: text})}
        defaultValue={this.state.selectedText}
    />

Good luck祝你好运

It's because your key on the map changes everytime it rerenders.这是因为每次重新渲染时,您在地图上的键都会更改。 Just use the index of the map iteration as key只需使用地图迭代的索引作为键

_getDetailElements = () => {

    return Object.keys(this.state.data).map((elem, index) => (
        <View key={index} style={styles.element}>
                <TextInput
                editable={this.state.editable}
                onChangeText={text => this.setState({seletedText: text})}
                value={this.state.selectedText}
                /> 
        </View>
    )
    );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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