javascript - React Native 无法在 render() 方法之外访问 this.props

标签 javascript reactjs react-native

我尝试在 clicked() 方法中访问 this.props,但它们未定义。如何通过 ListItemExample 类中的方法访问 this.props

我的目标是将 id 维护到显示 View 中,以显示单击的 ListItemExample 的详细信息 View 。

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();
  }

}

最佳答案

您需要执行onPress={this.clicked.bind(this)}

关于javascript - React Native 无法在 render() 方法之外访问 this.props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36462042/

相关文章:

javascript - 如何在 Controller 操作方法中运行/触发 javascript?

javascript - 如何在第一次使用复选框调用后重复 ajax 调用

javascript - 根据哈希 url 参数在页面加载时加载内容

javascript - React Native 中的 "Type"

javascript - React服务器端渲染,在开发环境中生成html

reactjs - manifest.json 中的环境变量 - Chrome 扩展

reactjs - react 延迟渲染

reactjs - React-Router-Dom 中的嵌套路由不起作用

react-native - 防止 React Native 缓存本地镜像

react-native - 如何使用 expo-av 在 React Native 中播放背景音频?