如何在反应js中访问这个变量?
问题描述:
父组件:如何在反应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?提前致谢。
答
而不是
<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
也因为data
和this.props.datarows[key]
将是相同的。
答
问题是,临时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>)
}