react中的类变量和函数变量之间的区别是什么

What is the difference between class variables and function variables in react

本文关键字:之间 区别 变量 是什么 类变量 react 函数      更新时间:2023-09-26

我在react中使用道具。发现了这个

var App = React.createClass({

        render: function(){
            var t = this.props.txt;
            return(<div>
                    <h1> {t}</h1>
                </div>);
        },
    });
    React.render(<App txt="hi"/>, document.body);

这很好,因为变量t在渲染函数中。但是当把t放在像这样的渲染函数之外时

var App = React.createClass({
// position of t is shifted here
    var t = this.props.txt;
        render: function(){
            return(<div>
                    <h1> {t}</h1>
                </div>);
        },
    });
    React.render(<App txt="hi"/>, document.body); 

这不起作用。由于我在React.render中直接调用App,而不是函数render,我希望App应该有可用的道具。我错过了什么?

我不太确定你为什么期望它能起作用。这只是无效的JavaScript。不能将变量声明放在对象文字中。您正在做的事情的简化示例:

var foo = { var bar = 42; };

这是一个语法错误。我建议阅读JavaScript教程来了解更多关于对象的信息。