admin管理员组

文章数量:1200394

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>
        );
    }
});

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>
        );
    }
});
Share Improve this question asked Dec 1, 2015 at 1:55 ChipeChipe 4,80110 gold badges38 silver badges65 bronze badges 2
  • 1 Try changing className{this.getClass} to className={'className' + this.getClass()}. – Hunan Rostomyan Commented Dec 1, 2015 at 2:00
  • Functions are called with (). If you don't call this.getClass, it won't work. – Felix Kling Commented Dec 1, 2015 at 2:36
Add a comment  | 

3 Answers 3

Reset to default 15

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>

本文标签: javascriptcall function inside of className reactjsStack Overflow