我刚开始使用react native开发,我很难通过props获得输入字段的值。
父母
class HomeContainerScreen extends Component {
state = {
userName:'',
passWord:''
}
userLogin=()=>{
alert(this.state.userName);
}
render() {
return (
<HomeScreen
userLogin = {this.userLogin}
userName = {this.state.userName}
passWord = {this.state.passWord}
/>
);
}
}
export default HomeContainerScreen;
孩子
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View,Image} from 'react-native';
import { Container, Content, Form, Input, Item, Label, Button} from 'native-base'
class HomeScreen extends Component {
render() {
return (
<Container>
<Content contentContainerStyle={{alignItems:'center', justifyContent:'center',top:150}}>
<Image style={{height:200, width:200, alignSelf:"center"}} source={require('../../assets/imgs/logo.jpg')}/>
</Content>
<Content>
<Form>
<Item stackedLabel>
<Label>Username</Label>
<Input onChangeText={(text=>this.setState({userName:this.props.userName}))}/>
</Item>
<Item stackedLabel last>
<Label>Password</Label>
<Input onChangeText={(text=>this.setState({passWord:this.props.passWord}))} />
</Item>
<Button
onPress={()=>this.props.userLogin()}
style={{width:'80%', alignSelf:'center',margin:20}} iconLeft block>
<Text style={{color:'white', fontSize:16}}>Sign In</Text>
</Button>
</Form>
</Content>
</Container>
);
}
}
export default HomeScreen
我已将其设置为在提交表单时获取值,但是在提交时会发生任何事情。 请提供任何有关如何使其正常工作的帮助。
答案 0 :(得分:0)
您要设置子组件(而不是父组件)的状态。您可以传递另一个回调函数作为道具,以便对this.setState的调用发生在父组件而不是子组件中。
父母:
setUserName = (userName) => {
this.setState({ userName: userName })
}
setPassWord= (passWord) => {
this.setState({ passWord: passWord})
}
内部render():
<HomeScreen
userLogin = {this.userLogin}
userName = {this.state.userName}
passWord = {this.state.passWord}
setUserName = {this.setUserName}
setPassWord = {this.setPassWord}
/>
并在子级:
<Input onChangeText={this.props.setUserName}/>
...
<Input onChangeText={this.props.setPassWord}/>
此外,此调用setState:
this.setState({ userName: this.props.userName })
不会做太多事情,因为它只是将状态设置为与现有状态相同的值。您可能需要将其设置为新值。