簡體   English   中英

未設置本機親本道具

[英]react-native parent prop not set

我正在從子元素的道具(MyTextField.js)設置父狀態(Login.js)。 從子元素來看,Prop的狀態表示已設置(即用戶名),但從父元素的角度(Login.js)來看,未設置狀態。 我很困惑 在MyTextField中,在change_text(text)函數中定義了以下內容

this.props.parent.state

但是從Login.js的login()函數中,未定義以下內容:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM