在ReactJS块中显示组件

时间:2019-04-29 22:23:28

标签: reactjs

我有2个按钮和div信息。在这种状态下,我记录了一个数组,其中包含键和组件。当我单击其中一个按钮时,我希望该组件显示在信息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;

2 个答案:

答案 0 :(得分:1)

首先,this.state.name未定义并且未分配任何值。 其次,您使事情变得简单。只需使用键为12并将对象的值作为场景中呈现的组件的对象

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;

答案 1 :(得分:0)

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>
    )
  }
}