Javascript React Native can';t在render()方法之外访问this.props

Javascript React Native can';t在render()方法之外访问this.props,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我正在尝试访问clicked()方法中的this.props,但它们未定义。如何通过ListItemExample类中的方法访问this.props 我的目标是将id维护到显示单击的ListItemExample的详细视图的show视图中 export default class Example extends Component { constructor() { super(); let ds = new ListView.DataSource({rowHasChang

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

我的目标是将
id
维护到显示单击的ListItemExample的详细视图的show视图中

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

}
导出默认类示例扩展组件{
构造函数(){
超级();
让ds=newListView.DataSource({rowHasChanged:(r1,r2)=>r1!==r2});
此.state={
数据源:ds,
孤岛加载:正确
};
}
componentDidMount(){
this.fetchData()
}
fetchData(){
Api.getPosts().then((resp)=>{
控制台日志(resp);
这是我的国家({
dataSource:this.state.dataSource.cloneWithRows(resp.posts),
孤岛加载:false
})
});
}
render(){
返回(
);
}
renderRow(邮政){
返回(
);
}
}
导出默认类ListItemExample扩展组件{
构造函数(){
超级();
}
render(){
返回(
);
}
点击(){
日志(“点击的道具”);
console.log(this.props);
Actions.openPost();
}
}

随着React从createClass转移到
ES6类
我们需要自己将
this
的正确值处理到我们的方法中,如下所述: 使用构造函数中的
this.clicked=this.clicked.bind(this)
更改代码,使方法绑定到构造函数中this的正确值

no autobinding
是React-guys为ES6课程精心设计的一步。
React.createClass
提供了自动绑定到正确上下文的功能。有关详细信息,请参见:

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

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

}
导出默认类ListItemExample扩展组件{
建造师(道具){
超级(道具);
}
render(){
返回(
);
}
点击=()=>{
日志(“点击的道具”);
console.log(this.props);
Actions.openPost();
}
}

在将FBSDK与React Native一起使用时,我遇到了相同的问题。而@fandro的回答几乎解释了很多

我有这个:

render() {
        const infoRequest = new GraphRequest(
            '/me',
            null,
            this.responseInfoCallback,
        );

        return (
            <View>
                <LoginButton
                    readPermissions={["email"]}
                    onLoginFinished={
                        (error, result) => {
                            if (error) {
                                console.log("Login failed with error: " + result.error);
                            } else if (result.isCancelled) {
                                console.log("Login was cancelled");
                            } else {
                                new GraphRequestManager().addRequest(infoRequest).start(1000);
                                console.log("Login was successful with permissions: " + result.grantedPermissions)
                            }
                        }
                    }
                    onLogoutFinished={() => alert("User logged out")}/>
            </View>
        );
    }

responseInfoCallback(error, result) {
        if (error) {
            alert('Error fetching data: ' + error.toString());
        } else {
            alert('Success fetching data: ' + result.toString());
            this.props.onLoginSuccess();
        }
    }
成功了。希望这有帮助。

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

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

<SomeComponent onClick={this.yourMethod.bind(this)} />
yourMethod(){
console.log(this.props)
}    

您可以为处理程序使用箭头函数,并自动绑定到词法范围。。。或者在调用时或者在构造函数中使用传统的.bind(this)。但请注意,我认为有一个答案使用了这种方法:您必须更改babel设置,并确保您具有“可选”:[“es7.classProperties”],以便类中的箭头函数正常工作。

在您试图进入另一个视图的组件中,您必须通过在导入组件的按下按钮中使用它来发送对象导航

范例

在视图中实现组件

组件模板

`<View>
       <Button  title={this.props.title} onPress={()=> 
       this.props.navigation.navigate("anotherAwesomeView")}/>
</View>`
`
this.props.navigation.navigate(“其他awesomeview”)}/>
`

这个问题是因为您尝试实现的组件没有在stackNavigation上定义,因此Method导航对您来说是不可用的,通过params传递这个对象导航器,您就可以访问它了

您的构造函数不应该将
props
作为参数传递给super吗
constructor(props){super(props)}
this.props在本例中未定义,除非我缺少一些明显的内容。若要修复“未定义”问题,请在构造函数中添加以下语句:this.clicked=this.clicked.bind(this);它将方法绑定到组件实例。希望有帮助!请添加更多详细信息或参考链接。您不应在呈现中绑定方法,它会创建该方法的实例并触发新呈现。saved my day:DYU应提供解释此答案缺少示例
`<View>
       <Button  title={this.props.title} onPress={()=> 
       this.props.navigation.navigate("anotherAwesomeView")}/>
</View>`