2017-04-03 21 views
1

父組件:如何在反應js中訪問這個變量?

render(){ 
    console.log("here2"); 
    var temp = []; 
    this.props.datarows.forEach((data, key) => { 
      temp = this.props.datarows[key] }) 
    return(
      <tr> 
       <ListColumn col = { this.temp } /> 
      </tr> 
     ) 
} 

ListColumn.py

import React, { Component } from 'react'; 
import _ from 'lodash'; 

export default class ListColumn extends Component{ 

    render(){ 
     var columns = []; 
     console.log("here3") 
     console.log(this.props.col); 
     // for (var key in this.props.col) 
     // { 
     // columns.push(<td>this.props.col[key]</td>) 
     // } 
     // console.log(columns); 
     // return(
     // columns 
     //) 
     return(
       <td>a</td> 
      ) 
    } 
} 

當我試圖打印的this.props.col值,則返回undefined,我如何訪問變量temp?提前致謝。

回答

0

而不是

<ListColumn col = { this.temp } />

使用

<ListColumn col = {temp } />

原因:在JS this是指自己的T對象他編碼,內部渲染方法this將引用反應組件。如果使用this.temp,它不會採用局部變量(在render方法中定義),所以不要使用this.temp使用temp(局部變量)。

還有一件事,如果你使用這樣的:

this.props.datarows.forEach((data, key) => { 
     temp = this.props.datarows[key] }) 

溫度將有this.props.datarows數組的最後一個值。我想,你想是這樣的:

this.props.datarows.forEach((data, key) => { 
     if(/*use some condition to filter out the value that you want to save in temp array*/){ 
      temp.push(data); 
     } 
} 

,或者如果你想分配相同的array到臨時變量,在這種情況下,不需要looping

建議:在地方的this.props.datarows[key]可以使用data也因爲datathis.props.datarows[key]將是相同的。

0

問題是,臨時decalared作爲var temp = [];但你路過this.temp 變化:<ListColumn col = { this.temp } />

<ListColumn col ={temp } /> 

所以,

render(){ 
    console.log("here2"); 
    var temp = []; 
    this.props.datarows.forEach((data, key) => { 
      temp = this.props.datarows[key] })//it should be temp.push(data) if you want to pass all datarows as props 
    return(
      <tr> 
       <ListColumn col = {temp } /> 
      </tr> 
     ) 
} 

2.

for (var key in this.props.col) 
    { 
     columns.push(<td>this.props.col[key]</td>) 
    } 

應該

for (var key in this.props.col) 
    { 
     columns.push(<td key={key}>{this.props.col[key]}</td>) 
    }