reactjs - 在渲染方法之外创建变量时出现错误
问题描述
为什么这在渲染方法之外不起作用
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"));
解决方案
因为在第一个中,您使用新提案定义了一个类属性: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>
推荐阅读
- bash - 在 bash 脚本中使用 grep 在远程主机上测试布尔条件
- java - 将 Spring MVC 与 aws documentDB 连接
- ios - 如何防止一次绘制多条线(swift)?
- haskell - 当输入值是浮点类型而不是 Haskell 中的整数类型时如何创建错误消息
- php - 通过 AJAX 发送的数据在 $_POST 中不可用
- linux - 使用 bash 在 Linux 中的文件夹中查找拥有文件的所有用户
- python - 当我访问该视图时,未处理我的其中一个视图中的代码
- reactjs - 如何在反应中将来自json的数据与“this.props”连接起来
- php - 如何修复注意:未初始化的字符串偏移量:0
- python - 选择网格的所有顶点以分别访问每个顶点