【问题标题】:React native properties反应原生属性
【发布时间】:2016-02-19 11:25:07
【问题描述】:

我真的很想了解属性以及它们是如何传递的。但我就是不能。无论我尝试什么,我都无法访问传递给组件的任何内容。

我有一个主页,其中包含一个 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:我实际上已经能够在我的应用程序的其他地方传递属性就好了。 并在传递给的组件内部使用它们。就是这一个让我伤心的组件

【问题讨论】:

  • 你不应该手动设置状态。
  • 详细说明。我一直在我的应用程序中执行此操作,并且到目前为止它一直在工作。我应该如何设置状态? (不使用通量、redux 操作等)该应用程序很简单,我在顶部加载所有数据,然后将其传递给需要它的页面。到目前为止,它一直在工作。显然我做的完全错了。仍在考虑常规应用程序,而不是反应流程。 PS所有的例子似乎完全按照我在这里所做的方式设置状态,所以当你说不要手动设置时,我不确定你的意思
  • 可以传递View和Text组件吗?
  • ?我没有尝试传递 View 或 Text 组件。我传递了 myUser JSON 对象
  • 可以加个rnplay fiddle吗?

标签: javascript properties react-native


【解决方案1】:

你需要做一些事情:

  1. 将 onComponentWillMount 更改为 componentWillMount

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

查看下面的代码,看看我在说什么:

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>
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 2016-03-03
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多