javascript 如何从反应组件中的反应函数中获取价值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29690595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:54:50  来源:igfitidea点击:

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

javascriptreactjs

提问by rex

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.

我是 Reacj.js 的新手,无法从函数中获取价值。我不确定我是否做得对。我需要函数表达式“func”来返回“from func”并替换{this.func}。不知道我错过了什么。

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/

我在http://jsfiddle.net/rexonms/409d46av/ 中有 js 小提琴

回答by Anders Ekdahl

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):

你快到了。请记住,JSX 中 { 和 } 中的所有内容都只是常规的 Javascript。要从 Javascript 中的函数获取返回值,您必须调用它。所以像这样(注意后面的括号this.func):

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