我目前正在嘗試創建一個按鈕onclick被附加到DOM元素的父組件。但是,我有一個問題得到初始循環工作。下面是我在做什麼,反應試圖循環通過狀態對象
class GenerateInvoice extends Component {
constructor(props) {
super(props);
this.state = {
'invoice': {
'items' : {}
}
};
this.onAddChild = this.onAddChild.bind(this);
}
render() {
const children = [];
for (var i = 0; i < Object.keys(this.state.invoice.items); i += 1) {
children.push(<InvoiceItemForm key={i} number={i} />);
};
return(
<div>
<a href="" onClick={this.onAddChild}>Add New Item</a>
{children}
</div>
)
}
onAddChild = (e) => {
e.preventDefault();
let invoice = this.state.invoice.items;
this.setState({ invoice : {'id' : 'INV001'} });
}
}
export default GenerateInvoice ;
然而,當我的客戶端與它onAddChild回調的按鈕,我得到
無法轉換未定義或爲空反對
爲什麼會這樣是?
這裏是我的測試項目中的鏈接,
https://codesandbox.io/s/0qx9w1qrwv
你的狀態對象鍵不必是字符串 –
@KarlTaylor:他們不是。 *屬性名*以字符串形式給出,true,這是可選的,但是無害的。 –
請使用Stack Snippets('[<>]'工具欄按鈕)使用** runnable ** [mcve]更新您的問題。 Stack Snippets支持React,包括JSX; [這是如何做一個](http://meta.stackoverflow.com/questions/338537/)。 –