首页 > 解决方案 > 如何在本机反应中从父级访问子组件值?

问题描述

我有一个具有以下结构的登录屏幕:

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() 方法。如何访问用户名和密码值以在登录屏幕中检查它们?

如果有人可以提供帮助,我将不胜感激。

标签: react-native

解决方案


尝试使用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;
    }

推荐阅读