简体   繁体   English

未设置本机亲本道具

[英]react-native parent prop not set

I am setting my parent state (Login.js) from a child element's Props (MyTextField.js). 我正在从子元素的道具(MyTextField.js)设置父状态(Login.js)。 From the child-element, the Prop's state says it is set (ie username), but from the parent's perspective (Login.js), the state is not set. 从子元素来看,Prop的状态表示已设置(即用户名),但从父元素的角度(Login.js)来看,未设置状态。 I'm very confused. 我很困惑 From MyTextField, the following is defined in the change_text(text) function 在MyTextField中,在change_text(text)函数中定义了以下内容

this.props.parent.state

But from Login.js 's login() function, the following is undefined: 但是从Login.js的login()函数中,未定义以下内容:

this.state

they should be pointing to the same thing. 他们应该指向同一件事。

MyTextField.js 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 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),是因为我需要 Login.js的登录功能绑定到自身(为什么我不知道),因为我从未在孩子(MyTextInput.js)上调用绑定 ,所以孩子工作得很好。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM