首页 > 解决方案 > 在渲染方法之外创建变量时出现错误

问题描述

为什么这在渲染方法之外不起作用

 class MyComponentClass extends React.Component{
        const n = Math.floor(Math.random()* 10 + 1);
        render(){
            return <h1>The number is {n}</h1>
    }
}
ReactDOM.render(<MyComponentClass/>,document.getElementById("app"));

但它在里面有效吗?

 class MyComponentClass extends React.Component{
        render(){
            const n = Math.floor(Math.random()* 10 + 1);
            return <h1>The number is {n}</h1>
    }
}
ReactDOM.render(<MyComponentClass/>,document.getElementById("app"));

标签: reactjscomponents

解决方案


因为在第一个中,您使用新提案定义了一个类属性:class-fields您不能const在那里使用。试试这样:

n = Math.floor(Math.random()* 10 + 1);

然后您可以通过以下方式访问它:

this.n

我不知道为什么这个答案被否决了,但是通过正确的设置,class-fields像 Babel 这样的插件,我们可以使用它。

class App extends React.Component {
  n = Math.floor(Math.random() * 10 + 1);
  render() {
    return <div>{this.n}</div>;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

class-fields这与不使用提案在构造函数中初始化属性没有什么不同。

class App extends React.Component {
  constructor( props ) {
    super( props );
    this.n = Math.floor(Math.random() * 10 + 1);
  }
  
  render() {
    return <div>{this.n}</div>;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>


推荐阅读