react-native - 如何在本机反应中从父级访问子组件值?
问题描述
我有一个具有以下结构的登录屏幕:
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() 方法。如何访问用户名和密码值以在登录屏幕中检查它们?
如果有人可以提供帮助,我将不胜感激。
解决方案
尝试使用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;
}
推荐阅读
- python - Python CSV 文件读取和保存
- c# - 相关删除性能问题
- machine-learning - 正在寻找合适的方法来根据残差或预测误差检查模型的优劣?
- regex - 使用 Perl 打印整个字符串,直到出现子字符串匹配
- google-app-engine - 如何思考微服务?
- machine-learning - WEKA 如何评估集群?
- angular - 在 Angular 中更新 CRUD 组件不保存数据
- java - 我们可以在tomcat 7上部署spring应用程序吗?
- node.js - 如何安装 npm sanitize
- java - ZK CKEditor 自定义插件与 Spring Boot