2017-04-03 4 views
1

부모 요소 :반응식 j에서이 변수에 어떻게 액세스합니까?

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의 값을 인쇄하려고

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, 그것은 undefined 반환, 내가 변수 TEMP에 액세스하려면 어떻게? 미리 감사드립니다.

답변

0

대신

이어야한다

<ListColumn col = { this.temp } />

사용

<ListColumn col = {temp } />

이유 : this가 t를 소유하고있는 오브젝트를 참조 JS에서 그 코드는 내부 렌더링 방법 this은 반응 구성 요소를 나타냅니다. this.temp를 사용하면 local 변수 (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는이 경우에 필요하지 않은 : 난 당신이 뭔가를하려는 생각합니다.

제안 : datathis.props.datarows[key]가 동일하기 때문에 this.props.datarows[key] 대신에 당신은 또한 data 사용할 수 있습니다.

0

문제는, 온도는 var temp = [];로 decalared되어 있지만 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>) 
    }