React Native无法访问render()方法之外的this.props

bot*_*bot 19 javascript reactjs react-native

我试图访问this.propsclicked()方法,但它们是未定义的.如何this.props通过ListItemExample类中的方法进行访问?

我的目标是维护id显示视图,显示单击的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();
  }

}
Run Code Online (Sandbox Code Playgroud)

fan*_*dro 28

你需要这样做 onPress={this.clicked.bind(this)}

  • 请添加更多详细信息或参考链接. (4认同)

Adi*_*ngh 11

随着React从createClass的转移,ES6 classes我们需要自己处理this我们方法的正确值,如下所述:http://www.newmediacampaigns.com/blog/refactoring-react-components-to-es6-classes 更改您的代码,以便在构造函数中使用this.clicked = this.clicked.bind(this)构造函数中的方法限制此方法的值

no autobinding是来自React家伙为ES6课程的刻意步骤.提供了自动绑定到正确的上下文React.createClass.有关详细信息,请访问:https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding

因此,基于此,您还可以将clicked方法更改为:

export default class ListItemExample extends Component {

 constructor(props) {
   super(props);
 }

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


      </View>
    </TouchableHighlight>
  );
 }

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

}
Run Code Online (Sandbox Code Playgroud)


Adi*_*ana 7

添加bind(this)将您的方法绑定到当前组件,例如

yourMethod(){
    console.log(this.props)
}    

<SomeComponent onClick={this.yourMethod.bind(this)} />
Run Code Online (Sandbox Code Playgroud)