use*_*364 11 ecmascript-6 reactjs
我停了一会儿,不知道哪里出错,请帮帮我
这是错误消息:
Warning: App(...): No `render` method found on the returned component instance: you may have forgotten to define `render`.
Uncaught TypeError: inst.render is not a function
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
import React from 'react';
import ReactDOM from 'react-dom';
console.log('Start')
export class App extends React.Component{
constructor(props) {
super(props);
console.log('getInitialState');
return { status:true }
}
toggleState(){
this.setState({status: !this.state.status})
}
render() {
console.log('render');
return (
<div>
<h1 onClick={this.toggleState}>Hello</h1>
</div>
);
}
}
ReactDOM.render(<App name='Vipul' />,document.getElementById('app'));
Run Code Online (Sandbox Code Playgroud)
Ale*_* T. 13
return从中删除constructor,并且state必须像这样的属性
constructor(props) {
super(props);
this.state = { status: true };
}
Run Code Online (Sandbox Code Playgroud)
看看这两个例子
function App() {
return { status: true }
}
App.prototype.render = function() {};
console.log(typeof new App().render);Run Code Online (Sandbox Code Playgroud)
function App() {
this.state = { status: true };
}
App.prototype.render = function() {};
console.log(typeof new App().render);Run Code Online (Sandbox Code Playgroud)
正如你在控制台中看到的,你在第一个例子中看到undefined它是因为构造函数App returns new custom object,而在第二个例子中你得到了正确的结果;