我是新手,想要编写一个简单的点击事件功能。
当我点击选择带有此类名称的span标记
处理小型原型代码 http://codepen.io/anon/pen/rxPvyr?editors=0110
尝试修复错误的实际代码库 http://codepen.io/kk-/pen/BjeLry
Line 16: Direct super call is illegal in non-constructor, use super."constructor"() instead
14 |
15 | constructor(props) {
> 16 | super(props);
| ^
17 |
18 | this.handleClick = this.handleClick.bind(this);
答案 0 :(得分:5)
有几种方法可以定义一个React类 - 你可能混合和匹配样式,当然不支持:
ES5 - 没有constructor()
方法,请使用getInitialState()
var React = require('react');
var SomeComponent = React.createClass({
getInitialState: function() {
return { message: 'hello world'};
},
render() {
return (
<div>{this.state.message}</div>
);
}
});
module.exports = SomeComponent;
ES6 - 否getInitialState()
,使用constructor()
此外,必须在调用super(props)
之前调用this
!
import React from 'react';
class SomeComponent extends React.Component {
constructor(props) {
super(props);
this.state({
message: 'hello world'
})
}
render() {
return (
<div>{this.state.message}</div>
);
}
}
SomeComponent.propTypes = {};
export default SomeComponent;
更新:如果有人忘记在super(props)
中呼叫constructor()
,但随后尝试访问this
,则会引发以下错误:{{1 }}:
'this' is not allowed before super()
ES6静态没有内部方法,只是隐含的Module build failed: SyntaxError: C:/_workspaces/hello-world/some-component.jsx: 'this' is not allowed before super()
20 | class SomeComponent extends React.Component {
21 | constructor(props) {
> 22 | this.state = {
| ^
23 | message: 'hello world'
24 | }
25 | }
render()