【问题标题】:How can I display a set of array on click of a button from it's child component using React如何使用 React 从其子组件单击按钮时显示一组数组
【发布时间】:2020-05-16 08:50:05
【问题描述】:

如何在使用 React 的子组件中单击按钮时显示一组数组?

由于我是 React 的新手,我一直在努力显示不警告或其他文本。下面是我目前写的代码。

import React, { Component } from 'react'
import LandingComponent from './LandingComponent'

class EmployeeList extends Component {
constructor(props) {
    super(props)

    this.state = {
         Employee : [
             {
                 ID: 1,
                 FirstName: 'Nancy',
                 LastName: 'Davolio',
                 Address: '507',
                 City: 'Seattle,WA',
                 PostalCode: '98122',
                 COuntry: 'USA'
             },
             {
                ID: 2,
                FirstName: 'Margaret',
                LastName: 'Peacock',
                Address: '507',
                City: 'Seattle,WA',
                PostalCode: '98122',
                COuntry: 'USA'
            }]}
            }
              showEmpList() {
              return {Employee: this.state.Employee}
}
             render() {
             return (
             <div>      
             <LandingComponent ListHandler={this.showEmpList}/>
            </div>
            )
       }
     }
                 export default EmployeeList

我的子组件有一个点击按钮,我想显示结果。

                 import React from 'react'

                 function LandingComponent(props) {
                   return (
                     <div>
                     <button>Display Not Found</button>
                     <button onClick={props.ListHandler}>Show Employee List</button>
                     </div>
                      )
                      }

                       export default LandingComponent

【问题讨论】:

  • 这个question 应该可以帮到你。
  • 不,这与我的要求无关。
  • 我尝试过这种方式,但另一方面它不会在 UI 上呈现任何内容,console.log 给了我想要的结果。所以请告诉我如何在 UI 上显示相同的输出? showEmpList(){ console.log(this.state.Employee) return (
    {this.state.Employee}
    ) }

标签: reactjs jsx


【解决方案1】:

设置一个变量来表示是否显示员工列表:

this.state = {
    ...
    showEmployeeList: false
}

声明一个将切换showEmployeeList的函数:

showEmpList () {
    this.setState({
        showEmloyeesList: !this.state.showEmployeesList,
    })
}

编写一个渲染员工的函数:

renderEmloyees (employees) {
    return (
        <div>
          {employees.map(e => (
            <div key=e.ID>
              {e.FirstName}
            </div>
          ))}
        </div>
  )
}

如果showEmployeeListtrue,则渲染员工:

<LandingComponent ListHandler={this.showEmpList}/>
{this.state.showEmployeeList && renderEmployees(this.state.Employee)}

【讨论】:

    猜你喜欢
    • 2020-09-14
    • 2018-04-08
    • 1970-01-01
    • 2018-07-29
    • 2020-04-24
    • 2018-05-04
    • 2022-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多