Js onClick response inside render

I have a ul lilist inside the method render, and lithere is an event onClickthat calls the function this.handleClickand the state changed

var InspirationFilter = React.createClass({
    getInitialState: function() {
        return {currentFilterText:"Top All Time", currentFilter:"top_all_time", showUl:false};
    },
    handleClick: function(filter, filterText){
        this.setState({currentFilterText:filterText, currentFilter:filter, showUl:!this.state.showUl});
    },
    render: function() {
        return (
            <ul>
                <li onClick={this.handleClick('top_all_time', 'Top All Time')}>Top All Time</li>
                  <li onClick={this.handleClick('top_this_week', 'Top This Week')}>Top Week</li>
                <li onClick={this.handleClick('top_this_month', 'Top This Month')}>Top Month</li>
            </ul>
        );
    }
});

But this code gives me an error

Warning: setState (...): cannot be updated during the existing state (for example, inside render). Rendering methods must be clean function props and state

I tried using bind with a click event like this,

return (
    <ul>
        <li onClick={this.handleClick.bind(this,'top_all_time', 'Top All Time')}>Top All Time</li>
        <li onClick={this.handleClick.bind(this,'top_this_week', 'Top This Week')}>Top  Week</li>
        <li onClick={this.handleClick.bind(this.'top_this_month', 'Top This Month')}>Top  Month</li>
    </ul>
);

The above error disappeared, but ran into another error, which looks like this:

Warning: bind (): you bind a component component to a component. React does this automatically for you in a high-performance way, so you can safely remove this call. See InspirationFilter

bind.

?

+3
3

, onClick , , ​​:

createClickHandler: function(filter, filterText){
    return function() {
        this.setState({...});
    }.bind(this);
},

render: function() {
    return (
        <ul>
            <li onClick={this.createClickHandler('top_all_time', 'Top All Time')}>Top All Time</li>
            <li onClick={this.createClickHandler('top_this_week', 'Top This Week')}>Top Week</li>
            <li onClick={this.createClickHandler('top_this_month', 'Top This Month')}>Top Month</li>
        </ul>
    );
}

. bind() this, .

?. , this.handleClick, ( ) .

+6

, , :

onClick={this.functionName(arg1, arg2)

, . , , , onClick, .

:

onClick={this.functionName.bind(this, arg1, arg2)}

, . ; ( , )

+2

, onClick.

You have a typo on the third <li>

return (
    <ul>
        <li onClick={this.handleClick.bind(this,'top_all_time', 'Top All Time')}>Top All Time</li>
        <li onClick={this.handleClick.bind(this,'top_this_week', 'Top This Week')}>Top  Week</li>
        <li onClick={this.handleClick.bind(this, 'top_this_month', 'Top This Month')}>Top  Month</li>
    </ul>
);

Check out this script https://jsfiddle.net/69z2wepo/20047/ It works on React 0.14

+1
source

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


All Articles