React.js - passed function "not function" Error

I am trying to pass props from a child component to a parent component, but for some reason I get the error "TypeError: this.props.onClick is not a function" in the js console after clicking on rendering the child components.

Basically, what I'm trying to do is manage a list of categories in which a subcomponent of one category has the "selected" support as true and is updated correctly every time you click on the li category.

Here is the jsfiddle with the code: http://jsfiddle.net/kb3gN/8023/

I really don't feel like I understand how to use React.js effectively, so any help is appreciated!

Best regards and thanks,

bnunamak

The code:

var CategoryList = React.createClass({ getInitialState:function(){ return { items:[ ["cat1", false], ["cat2", true] ], lastToggled:["cat2"] } }, //Function passed to child (changes items state) handleClick:function(child){ var tempItems = this.state.items; if(this.state.lastToggled[0] === child.props.name){ var index = this.getInd(this.state.tempItems, child.props.name); tempItems[index][1] = !tempItems[index][1]; this.setState({items: tempItems}); }else{ var newIndex = this.getInd(this.state.tempItems, child.props.name); tempItems[newIndex][1] = !tempItems[newIndex][1]; var oldIndex = this.getInd(this.state.tempItems, this.state.lastToggled[0]); tempItems[oldIndex][1] = false; this.setState({items: tempItems, lastToggled: tempItems[newIndex][0]}); } }, //getInd not relevant to problem getInd:function(arr, elname){ for (var i = arr.length - 1; i >= 0; i--) { if(arr[i][0] === elname){ return i; } }; return -1; }, render:function(){ return (<ul className="category-list"> { this.state.items.map(function(item){ return <Category onClick={this.handleClick} name={item[0]} selected={item[1]} />; }) } </ul>) } }); var Category = React.createClass({ render:function(){ if(this.props.selected){ return (<li onClick={this.propogateClick} className="selected">{this.props.name}</li>); }else{ return (<li onClick={this.propogateClick}>{this.props.name}</li>); } }, propogateClick: function(){ this.props.onClick(this); } }); React.renderComponent(<CategoryList/>, document.getElementById('example')); 
+5
source share
2 answers

You can use bind to solve this problem.

 this.state.items.map(function(item){ return <Category onClick={this.handleClick} name={item[0]} selected={item[1]} />; }.bind(this)) 
+2
source

There seems to be a problem with the scope here:

 this.state.items.map(function(item){ return <Category onClick={this.handleClick} name={item[0]} selected={item[1]} />; }) 

If I remove the external card and add the general category, it works (well, there are other problems, but the click function succeeded).

I will need to pass the function in another way (without using this.handleClick).

0
source

Source: https://habr.com/ru/post/1207521/


All Articles