gpt4 book ai didi

javascript - this.props 返回未定义?

转载 作者:行者123 更新时间:2023-12-01 02:38:47 25 4
gpt4 key购买 nike

我目前正在通过 props 将数据传递到我的组件中,由于某种原因,它显示为未定义。从我的父组件 Angular 来看,我有以下第 2 遍 Prop :dataheader

class ContractTable extends Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}

render() {
return (
<div>
<p></p>
<MuiThemeProvider>
<TableTest
data={this.state.data}
header={[
{
name: "First Name",
prop: "firstName"
},
{
name: "Last Name",
prop: "lastName"
},
{
name: "Age",
prop: "age"
},
{
name: "Height",
prop: "height"
},
{
name: "Address",
prop: "address"
}
]}
/>
</MuiThemeProvider>
<p></p>
</div>
);
}

我尝试获取 Prop 并将其设置为我的状态,但是当我记录 this.props.datathis.props.header 时,它返回未定义。为什么是这样?

import React, { Component } from 'react';
import {
Table,
TableBody,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn,
} from 'material-ui/Table';

class TableTest extends Component {
constructor(props) {
super(props);

this.state = {
data: props.data,
header: props.header
}

this.row = this.row.bind(this);
}

row = (currentValue, index, header) => (
<TableRow key={`t-${index}`}>
{
header.map((headerName, index) => (
<TableRowColumn key={`trc-${index}`}>
{currentValue[headerName.prop]}
</TableRowColumn>
))
}
</TableRow>
);

render() {
return 'hello'
}
}

export default TableTest;

最佳答案

更新:看看 https://jsfiddle.net/nroLmghv/

刚刚渲染了简单的表头。

将 props 传递给 state 并不是一个好方法。

<小时/>

我创建了一个片段。它看起来很有效。看看你哪个地方有问题。或者提供 MuiThemeProviderTableTest 完整代码。

class Example extends React.Component {
constructor(props) {
super(props)
this.state = {
// mock value
data: "some value"
}
}

render() {
return <div>
<TableTest
data={this.state.data}
header={[
{
name: "First Name",
prop: "firstName"
},
{
name: "Last Name",
prop: "lastName"
},
{
name: "Age",
prop: "age"
},
{
name: "Height",
prop: "height"
},
{
name: "Address",
prop: "address"
}
]}
/>
</div>;
}
}

class TableTest extends React.Component {
constructor(props) {
super(props);
this.state = {
data: this.props.data,
header: this.props.header
}

console.log(this.state.data)
console.log(this.state.header)
}

render() {
return <div></div>;
}
}

ReactDOM.render(
<Example />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root">
</div>

关于javascript - this.props 返回未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47710825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com