React Native can'无法在render()方法之外访问this.ops

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

本文关键字:方法 ops this 访问 render can Native React      更新时间:2024-02-15

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

我的目标是将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();
  }
}

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

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

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

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

我在使用带有React Native的FBSDK时遇到了同样的问题。而@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();
        }
    }

this.props.onLoginSuccess()的调用导致了"undefined不是一个评估this.props.onLoginScess()的对象"的问题。因此,当我将const infoRequest = new GraphRequest(...)中的代码更改为包含.bind(this):时

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

它奏效了。希望这能有所帮助。

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

在您试图进入另一个视图的组件中,您必须通过在组件导入的onPress中使用此选项来发送对象导航

示例

实现视图中的组件

<CardComponent title="bla bla" navigation={this.props.navigation} />

组件模板

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

这个问题是因为你试图实现的组件没有在stackNavigation上定义,因此方法导航对你来说是不可用的,通过参数传递这个对象导航器,你可以访问它