我试图在 render 方法上显示内容,但代码无法在 React JS 中执行 onClick
。我一直在 Udemy 上学习这门类(class)。
import React, { Component } from 'react';
import './App.css';
import New from './New/New';
import Old from './Old/Old';
class App extends Component {
state = {
theirName : [
{name:'Faisal', pind:'bhouch', age: 23},
{name:'Haroon', pind:'Harrror', age: 17}
],
showPerson : false,
}
togglePersonHandler =()=>{
//this.setState({showPerson : !this.state.showPerson})
const doesshow = this.state.showPerson;
this.setState({showPerson : !doesshow});
}
switchNameHandler = (noname) =>{
this.setState({
theirName : [
{name:'Faisal', pind: noname, age: 20},
{name:'Haroon', pind:'england', age: 17}
]
});
}
render() {
let persons = null;
if (this.state.showPerson === true){
persons =(
<div>
<New name={this.state.theirName[0].name} pind={this.state.theirName[0].pind} age={this.state.theirName[0].age}> </New>
<Old name={this.state.theirName[1].name} pind={this.state.theirName[1].pind} age={this.state.theirName[1].age}></Old>
</div>
);
}
return (
<div className="App">
<h1>Click on this to show content</h1>
<button onClick={this.togglePersonHandler} >switch</button>
<persons />
</div>
);
}
}
export default App;
在我做错的地方时代码中也没有错误或错误?
最佳答案
我认为你的返回不是渲染函数的一部分。希望这有帮助!
render() {
let persons = null;
if (this.state.showPerson === true){
persons =(
<div>
<New name={this.state.theirName[0].name} pind={this.state.theirName[0].pind} age={this.state.theirName[0].age}> </New>
<Old name={this.state.theirName[1].name} pind={this.state.theirName[1].pind} age={this.state.theirName[1].age}></Old>
</div>
);
}
// } =>render function gets closed. It should be closed after return statement
// } => extra brackets
// { Also, return should be inside of render
return (
<div className="App">
<h1>Click on this to show content</h1>
<button onClick={this.togglePersonHandler} >switch</button>
<persons />
</div>
);
} //closing for render
} //closing for App
关于javascript - 使用状态时,渲染在 React JS 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60088263/