Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native can't access this.props outside of render() method

Tags:

I am trying to access this.props in the clicked() method, but they are undefined. How can I access this.props through the methods in the ListItemExample class?

My goal is to maintain the id into the show view that shows the detail view for a clicked ListItemExample.

export default class Example extends Component {

  constructor() {
    super();
    let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

    this.state =  {
      dataSource: ds,
      isLoading: true
    };
  }

  componentDidMount() {
    this.fetchData()
  }

  fetchData() {

    Api.getPosts().then((resp) => {
      console.log(resp);
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(resp.posts),
        isLoading: false
      })
    });

  }

  render() {
    return (
      <View style={styles.container}>

          <ListView
              dataSource={this.state.dataSource}
              renderRow={this.renderRow.bind(this)}
              style={styles.postList}
              />

      </View>
    );
  }

  renderRow(post) {
    return (
        <PostListItem
          id={post.id}
          coverImage={post.cover_image}
          title={post.title}
          lockedStatus={post.status}
          time={post.time} />
    );
  }

}



export default class ListItemExample extends Component {

  constructor() {
    super();
  }

  render() {
    return (
      <TouchableHighlight onPress={this.clicked} >
        <View style={styles.postItem}>


        </View>
      </TouchableHighlight>
    );
  }

  clicked() {
    console.log("clicked props");
    console.log(this.props);
    Actions.openPost();
  }

}
like image 750
botbot Avatar asked Apr 06 '16 20:04

botbot


People also ask

What is render() in React?

React renders HTML to the web page by using a function called render(). The purpose of the function is to display the specified HTML code inside the specified HTML element. In the render() method, we can read props and state and return our JSX code to the root component of our app.

Can I use props without constructor?

Without adding a constructor you can stil use this. props in your components.

How do I access my props outside render?

You have to store the props in a static component in render method and then pass the props to the function declared outside the render method. Save this answer.

What is the render props method?

The term “render prop” refers to a technique for sharing code between React components using a prop whose value is a function. A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.


1 Answers

You need to do onPress={this.clicked.bind(this)}

like image 139
fandro Avatar answered Sep 22 '22 12:09

fandro