reactjs - React function passed to child through props is undefined -
i trying pass selectnotebook
notebooknav
used in onclick()
function. can see selectnotebook
in prop in react dev tools, whenever click button, error uncaught typeerror: cannot read property 'selectnotebook' of undefined(…)
.
this parent component:
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> ); } });
this child component:
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> ); } });
<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>
the problem transform function passed map
create it's own scope, this
undefined. fix this, array.prototype.map takes second argument scope can pass this
outer scope:
{notebooks.map(function (notebook) { ... }, this)
if target environment supports can use arrow function, implicitly uses outer scope:
{notebooks.map((notebook) => { ... })}
Comments
Post a Comment