0
我正在從子元素的Props(MyTextField.js)設置我的父狀態(Login.js)。從子元素來看,Prop的狀態表明它已被設置(即用戶名),但從父母的角度來看(Login.js),狀態沒有設置。我很困惑。 從myTextField將,下面是在change_text(文本)功能react-native parent prop not set
this.props.parent.state
但從Login.js的登錄()函數定義,以下是不確定的:
this.state
他們應該指向到同樣的事情。
MyTextField.js
export default class MyTextField extends Component
{
constructor(props)
{
super(props);
this.state = {text: props.text, style:styles.unfocused};
this.state[this.props.name] = '';
}
change_text(text)
{
this.setState({text:text});
if(this.props.parent && this.props.name)
{
this.props.parent.state[this.props.name] = text;
}
else
console.log('no parent or name');
}
render()
{
return (
<TextInput style={this.state.style} multiline={false} maxLength={100} onFocus={() => this.setState({style:styles.focused}) } onBlur={() => this.setState({style:styles.unfocused}) } onChangeText={(text) => this.change_text(text)} value={this.state.text} placeholder={this.props.placeholder}
/>)
}
}
MyTextField.propTypes =
{
text: React.PropTypes.string,
parent: React.PropTypes.object,
name: React.PropTypes.string
};
Login.js
import React, { Component, PropTypes } from 'react';
import { View, Text, Button, TextInput,TouchableHighlight,StatusBar,StyleSheet } from 'react-native';
import MyButton from './MyButton';
import MyTextField from './MyTextField';
export default class Login extends Component
{
constructor(props)
{
super(props);
this.state =
{
username:'',
password:'',
};
}
login()
{
console.log('login',JSON.stringify(this.state,null,2));
}
render()
{
return (
<View style={{flex: 1,flexDirection: 'column',justifyContent: 'space-between',margin:10}}>
<View style={{backgroundColor: 'powderblue'}} />
<MyTextField name='username' placeholder="User Name" parent={this} />
<MyTextField name='password' placeholder="Password" parent={this} />
<MyButton onPress={this.login} title='Login'/>
</View>
);
}
}