我試圖通過selectNotebook
到notebookNav
以用於onClick()
函數。我可以在我的React開發工具中看到selectNotebook
,但每當我點擊一個按鈕時,就會收到錯誤Uncaught TypeError: Cannot read property 'selectNotebook' of undefined(…)
。通過道具傳遞給孩子的反應函數未定義
這是我的父組件:
var App = React.createClass({
getInitialState: function() {
return {
notebooks: this.props.notebooks,
nav: this.props.nav
};
},
selectNotebook: function(id) {
const nav = {...this.state.nav};
nav[notebook] = this.props.notebooks[id];
this.setState({nav})
},
render: function() {
return (
<div style={{"height": "100%"}}>
<NotebookNav
notebooks={this.props.notebooks}
selectNotebook={this.selectNotebook}
>
</NotebookNav>
<Technique></Technique>
</div>
);
}
});
這是子組件:
var NotebookNav = React.createClass({
render: function() {
notebooks = this.props.notebooks;
return (
<div className="col-md-4">
<div className="panel panel-info">
<div className="panel-heading">
<h4 className="panel-title">Your Notebooks</h4>
</div>
<div className="panel-body">
<ul className="breadcrumb"
style={{"backgroundColor": "#fff", "marginBottom": "0"}}
>
<li className="active">
notebooks
</li>
</ul>
<ul className="nav nav-pills nav-stacked">
<div className="btn-group-vertical" style={{"width": "100%"}}>
{notebooks.map(function (notebook) {
return(
<li
key={notebook.id}
className="btn btn-block btn-raised btn-lg"
onClick={() => this.props.selectNotebook(notebook.id)}
>
{notebook.name}
</li>
);
})}
</div>
</ul>
</div>
</div>
</div>
);
}
});
感謝您的建議,但是當使用'createClass'而不是es6'擴展React.component'時,'this'被自動綁定。如果您在使用'createClass'時按照您的建議出價,它會向您發出錯誤。 –