【发布时间】:2020-05-21 05:23:45
【问题描述】:
我有一个显示两个 TextInputs 的类,最初值是空的,但随后另一个组件通过道具发送值。问题是我也想在这个组件中编辑它们,但它不能正常工作。当我收到值然后更改它们时,如果我使用 Button 复制它们,它不会复制状态中的值。 我添加了一个 userInitialized 和 passInitialized 布尔值,如果通过键入而不是传递道具更改值,则它们设置为 true。 任何想法?谢谢。
export default class BotomQRScanner extends Component{
constructor(props){
super(props);
this.state = {
userField: this.props.user,
userInitialized: false,
passInitialized: false,
passwordField: this.props.pass
}
}
handleUserChange(value){
this.setState({userField: value, userInitialized: true});
}
handlePasswordChange(value){
this.setState({passwordField: value, passInitialized: true});
}
render(){
return (
<View style={{height: '100%', width: '100%', alignItems: 'center', justifyContent: 'space-around'}}>
<View style={{flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center'}}>
<TextInput
onChangeText={(value) => this.handleUserChange(value)}
style={{textAlign: 'center', fontSize: 16, height: 50, width: 200}}
autoCapitalize = 'none'
autoCorrect={false}
selectTextOnFocus={true}
placeholder={'username'}
selectionColor={'#428AF8'}
value={this.state.userInitialized? this.state.userField : this.props.user}
/>
<Button
title="copy"
onPress={() => {
Clipboard.setString(this.state.userInitialized? this.state.userField : this.props.user)
}}
/>
</View>
<View style={{flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center'}}>
<TextInput
onChangeText={(value) => this.handlePasswordChange(value)}
style={{textAlign: 'center', fontSize: 16, height: 80, width: 200}}
autoCapitalize = 'none'
autoCorrect={false}
selectTextOnFocus={true}
placeholder={'password'}
value={this.state.passInitialized? this.state.passField : this.props.pass}
/>
<Button
title="copy"
onPress={() => {
Clipboard.setString(this.state.passInitialized? this.state.passField : this.props.pass)
}}
/>
</View>
</View>
);
}
}
【问题讨论】:
-
你的handleUserChange和handlePasswordChange函数没有绑定,请绑定或者使用箭头函数。
-
@MuhammadHaseeb 仍然不起作用,有时当我想用按钮复制密码并粘贴它时,什么都没有,不复制值。奇怪的是正确地复制了用户。但我记得昨天情况正好相反。
-
您能否创建一个代码的最小示例并分享它,即 codeSandbox?
标签: javascript reactjs react-native