我有2个按钮和div信息。在状态中,我记录了一个数组,其中包含密钥和组件。当我点击其中一个按钮时,我希望组件显示在info div中。哪里出错了?
import React, { Component } from 'react';
import Donald from '/.Donald';
import John from '/.John';
class Names extends Component {
state = {
array :[
{keys:1, name:<Donald/> },
{keys:2, name:<John/> }]
};
searchName = (keys)=>{
const arrr = this.state.array.filter(item => item.keys === keys);
this.setState({array : arrr})
return this.state.arrr;
}
searchInfo =()=>{
const cont = this.state.array.filter(item => item.name === this.state.name);
return cont;
}
render() {
return(
<div>
<div className="info">{this.searchInfo(this.state.name)}</div>
<div>
<button onClick={ () => this.searchName(1) }>My name Donald</button>
<button onClick={ () => this.searchName(2)}>My name John</button>
</div>
</div>
)
}
}
export default Names;
首先,this.state.name
未定义且未分配任何值。其次,你简单地复杂化了事情。简单地使用带有键的对象作为1
,2
和值作为渲染组件,如在您的场景中
import React, { Component } from 'react';
import Donald from '/.Donald';
import John from '/.John';
class Names extends Component {
state = {
key: 1
};
components = {
1: <Donald/>,
2:<John/>
};
showComponent = key => {
this.setState({ key });
};
render() {
return(
<div>
<div className="info">{this.components[this.state.key]}</div>
<div>
<button onClick={ () => this.showComponent(1) }>My name Donald</button>
<button onClick={ () => this.showComponent(2)}>My name John</button>
</div>
</div>
)
}
}
export default Names;
import React, { Component } from 'react'
import Donald from '/.Donald'
import John from '/.John'
class Names extends Component {
state = {
showDonald: false,
showJohn: false
}
render() {
return (
<div>
<div className="info">
{this.state.showDonald ? <Donald /> : null}
{this.state.showJohn ? <John /> : null}</div>
<div>
<button onClick={() => this.setState({ showDonald: true, showJohn: false })}>My name Donald</button>
<button onClick={() => this.setState({ showJohn: true, showDonald: false })}>My name John</button>
</div>
</div>
)
}
}