我知道这个问题存在一个重复的问题,但这并没有证明对我有帮助。这是我的index.js:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<header class="main-nav"></header>
<div class="marker"></div>
</div>
这是错误:
import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';
class App extends React.Component {
constructor(props) {
super(props);
this.formSet = this.formSet.bind(this);
this.state = { editing: false, ename: "Edit", sname: "Save" };
}
formNormal() {
return (
<div>
<h4>{this.state.ename}</h4>
<p>Hello there!</p>
<button onClick={!this.formSet}>{this.props.etext}</button>
</div>
);
}
formEdit() {
return (
<div>
<h4>{this.state.sname}</h4>
<input type="textarea" defaultValue="Hello there!" />
<button onClick={this.formNormal}>{this.props.stext}</button>
</div>
);
}
formSet() {
return (this.setState({ editing: true }));
}
render() {
if (this.state.editing) {
return (this.formEdit);
}
else {
return (this.formNormal);
}
}
}
render(<App etext="Edit" stext="Save" />, document.getElementById('root'));
我是React的新手。
答案 0 :(得分:0)
错误对:
开关
return (this.formEdit)
至
return (this.formEdit())
和return (this.formEdit);
至return (this.formEdit());
。
this.formEdit
是一个函数,要在页面中呈现的内容是该函数返回的内容,即通过this.formEdit
执行this.formEdit()
函数。您不能呈现函数,但是可以呈现函数返回的内容,即有效的JSX。
绑定使用不正确。所以我只是添加了整个示例,它将起作用。看看。
class App extends React.Component {
constructor(props) {
super(props);
this.formSet = this.formSet.bind(this);
this.formNormal = this.formNormal.bind(this);
this.formEdit = this.formEdit.bind(this);
this.state = { editing: false, evalue: 'Hello There!', ename: this.props.eText, sname: this.props.sname };
}
formNormal() {
return (
<div>
<h4>{this.state.ename}</h4>
<p>{this.state.evalue}</p>
<button onClick={this.formSet}>{this.props.etext}</button>
</div>
);
}
handleChange = (e) => {
this.setState({
evalue: e.target.value,
});
}
formEdit() {
return (
<div>
<h4>{this.state.sname}</h4>
<input type="textarea" value={this.state.evalue} onChange={this.handleChange} />
<button onClick={this.formSet}>{this.props.stext}</button>
</div>
);
}
formSet() {
this.setState({ editing: !this.state.editing });
}
render() {
if (this.state.editing) {
return (this.formEdit());
}
else {
return (this.formNormal());
}
}
}
ReactDOM.render(
<App etext="Edit" stext="Save" />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js"></script>
<div id="root">
<!-- This element's contents will be replaced with your component. -->
</div>