简体   繁体   中英

call function inside of className react.js

How do I call the function for getClass for the className inside this example? The way I have it written out does not seem to call getClass .

var CreateList = React.createClass({
    getClass: function() {
        //some code to return className
    },
    render: function() {
        return(
            <div className{this.getClass}>Example</div>
        );
    }
});

You're referencing the instance of the getClass() function as opposed to calling the function. Try tweaking it like so:

render: function() {
    return(
        <div className={this.getClass()}>Example</div>
    );
}

className{this.getClass} won't compile. Try this:

var CreateList = React.createClass({
    getClass: function() {
        //some code to return className
    },
    render: function() {
        return(
            <div className={this.getClass()}>Example</div>
        );
    }
});

If you want the div to have a class name that starts with 'className', then prepend that string to the result of the call: className={'className' + this.getClass()} .

functional component

const statusColor = () => {
    return 'red';
  };
<span className={statusColor()}>your text</span>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM