反应原生属性

时间:2016-02-19 11:25:07

标签: javascript properties react-native

我真的试图围绕属性和他们如何传递反应。但我不能。无论我尝试什么,我都无法访问传递给组件的任何内容。

我有一个包含MyProfile组件的主页面,我将JSON对象传递给用户属性。

var myUser = {"name":"test","avatar":"imagelinketc"}

<MyProfile user={myUser} />

然后在MyProfile组件中,我根据传递的属性设置用户。但它没有用!?

class MyProfile extends Component {
  constructor(props){
    super(props);
    this.state = {
      user: props.user,
      loaded:false
    };
  }

  render(){
    return(
      <View>
        <Text>{this.state.user.name}</Text>
      </View>
    )
  }
}

返回null / undefined。

然后我尝试了这个......

class MyProfile extends Component {
  constructor(props){
    super(props);
    this.state = {
      user: null,
      loaded:false
    };
  }

  onComponentWillMount(){
    this.setState({
      user:this.props.user,       
      loaded:true
     });
  }

  render(){
    return(
      <View>
        <Text>{this.state.user.name}</Text>
      </View>
    )
  }
}

仍未定义。 我也尝试过,直接设置一个this.user属性。在this.state之外,仍未定义。我似乎无法将属性传递给MyProfile。 无论我通过什么,最终都是空的。我完全倒退吗?

如何将用户从第一页传递到“个人资料”页面!! ??被困在这几个小时。

PS:我实际上已经能够在我的应用程序中的其他地方传递属性了。 并在传递给组件的内部使用它们。只是这一个让我悲伤的组件

1 个答案:

答案 0 :(得分:4)

您需要做一些事情:

  1. 将onComponentWillMount更改为componentWillMount

  2. 在传递属性并在构造函数中设置它们时,需要将它们引用为this.props而不是props

  3. 查看以下代码,了解我在谈论的内容:

    var user = { name: 'Chris', age: 22, location: 'California' }
    
    class App extends Component {
    
      constructor(props){
        super(props)
        this.state = {
          user: user
        }
      }
    
      render() {
        return (
          <View style={styles.container}>
            <User user={ this.state.user } />
          </View>
        );
      }
    }
    
    class User extends Component {
      constructor(props){
        super(props)
        this.state = {
          user: this.props.user
        }
      }
    
      render() {
        return <View>
                  <Text>{ this.props.user.name }</Text>
                  <Text>{ this.props.user.age }</Text>
                  <Text>{ this.props.user.location }</Text>
               </View>
      }
    }