不设置反应母亲主张



我正在从子元素的props(mytextfield.js)设置父状态(login.js)。从儿童元素中,道具的状态表示已设置(即用户名),但从父母的角度(login.js)设置,未设置状态。我很困惑。从myTextfield,以下是在change_text(text)函数

中定义的
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>
  );
 }
}

这个原因是可以从孩子(mytextinput.js)而不是login.js访问父母的状态(login.js),是因为我需要 bind 录。JS的登录函数本身(为什么我不知道),因为我从未在孩子(mytextinput.js)上打电话 bind ,孩子的工作正常。

this.login = this.login.bind(this);

最新更新