我有一个具有以下结构的登录屏幕:
import Logo from '../components/Logo'
import Form from '../components/Form';
export default class Login extends React. Component {
<View style={styles.container} >
<Logo/>
<Form type="login"/>
<View style={styles.signUpTextCont}>
...
</View>
</View>
这是我的表单组件:
export default class Form extends React.Component {
constructor (props){
super(props)
this.state = {
username : '',
password : ''
}
}
handleChangeUsername = (text) => {
this.setState({ username: text })
}
handleChangePassword = (text) => {
this.setState({ password: text })
}
render() {
return (
<View style={styles.container} >
<TextInput
ref={(input) => { this.username = input }}
onChangeText = {this.handleChangeUsername}
value = {this.state.username}
/>
<TextInput
ref={(input) => { this.password = input }}
onChangeText = {this.handleChangePassword}
value = {this.state.password}
/>
<TouchableOpacity style={styles.button}>
<Text style={styles.buttonText}>{this.props.type}</Text>
</TouchableOpacity>
</View>
);
}
}
现在,我想在“登录”屏幕(父级)中使用一个checkLogin()方法。 如何在登录屏幕中访问用户名和密码值以进行检查?
如果有人可以帮助我,我将不胜感激。
答案 0 :(得分:3)
尝试使用ref
关键字访问子值。
<View style={styles.container} >
<Logo/>
<Form type="login"
ref={'login'}/>
<View style={styles.signUpTextCont}>
...
</View>
</View>
要在父级中访问子级组件值:
onClick = () =>{
//you can access properties on child component by following style:
let userName = this.refs['login'].state.username;
let password = this.refs['login'].state.password;
}
答案 1 :(得分:0)
您可以使用回调将用户名和密码发送给父级,例如以下示例代码:
表格:
handleChangeUsername = (text) => {
this.setState({ username: text })
this.props.userChange(text)
}
handleChangePassword = (text) => {
this.setState({ password: text })
this.props.passChange(text)
}
登录:
添加两个名为user的状态并通过和:
setUser = (text) => {
this.setState({user:text})
}
setPass = (text) => {
this.setState({pass:text})
}
checkLogin = () => {
// check user and pass state...
}
<Form
type="login"
userChange = {(text) => { this.setUser(text) } }
passChange = {(text) => { this.setPass(text) } }
/>
现在,用户和密码处于登录状态,您可以检查它。 希望对您有帮助