简体   繁体   中英

How to get value from a react function within a react component

I am new to Reacj.js and having trouble getting value back from a function. I am not sure if I am doing it right. I need the function expression "func" to return "from func" and replace {this.func}. Not sure what I am missing.

var Hello = React.createClass({

    func: function(){
        return 'from func';
    },

    render: function() {
        return <div>
                    <div>Props: {this.props.name}</div>
                    <div>Function: {this.func}</div>
               </div>;
    }
});

React.render(<Hello name="from props" />, document.getElementById('container'));

I have the js fiddle in http://jsfiddle.net/rexonms/409d46av/

You're almost there. Remember that everything inside { and } in JSX is just regular Javascript. And to get the return value from a function in Javascript, you have to call it. So something like this (notice the parens after this.func ):

return (
  <div>
    <div>Props: {this.props.name}</div>
    <div>Function: {this.func()}</div>
  </div>
);

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