簡體   English   中英

React Native 無法在 render() 方法之外訪問 this.props

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

我試圖在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)}

隨着的轉變,從createClass反應ES6 classes我們需要處理的正確值this我們對我們自己的方法,這里提到: http://www.newmediacampaigns.com/blog/refactoring-react-components-to- es6-classes在構造函數中使用this.clicked = this.clicked.bind(this)更改您的代碼以將方法綁定到構造函數中的 this 的正確值

no autobinding是 React 人員為 ES6 類故意no autobinding的步驟。 React.createClass 提供了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)} />

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

並調用this.props.onLoginSuccess()導致問題“未定義不是評估 this.props.onLoginSuccess() 的對象”。 因此,當我更改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 上定義,因此您無法使用方法導航,並且通過 params 傳遞此對象導航器您可以訪問它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM