【问题标题】:Display elements on button click in React在 React 中单击按钮时显示元素
【发布时间】:2018-01-13 22:13:50
【问题描述】:

我是 React 新手,我必须显示一些从数据库加载的书籍的数据,就像我在 render() 中所做的那样。当我单击“所有书籍”按钮时,我想这样做。我应该在 getAllBooks 函数中写什么而不是在 render() 中写代码?我真的找不到正确的方法。谢谢! ,

import React, {Component} from 'react'
import BookStore from './BookStore'
import {EventEmitter} from 'fbemitter'

const emitter= new EventEmitter()
const store= new BookStore(emitter)

class BookList extends Component{
    constructor(props){
        super(props)
        this.state= {
            books: []
        }
    }
    componentDidMount(){
        store.getAll()
        emitter.addListener('BOOK LOAD', ()=>{
            this.setState({books: store.content})
        })

        this.getAllBooks = this.getAllBooks.bind(this);
    }

    getAllBooks(){

    }

    render(){
        return (
            <div>
            <div>
            <h3>The Books:</h3>
            <br></br>
            <div>
            {
            this.state.books.map((b)=>
            <div>{b.title +' by '+ b.author}</div>
            )
            }
            </div>
            </div>
            <input type="button" value="All Books" onClick={this.getAllBooks}/>

            </div>
        )
    }
}

export default BookList

【问题讨论】:

  • 渲染中的代码有什么问题?
  • 没什么,它工作正常,但我想在点击我的按钮时执行它。
  • 把你的代码移到那里
  • 这似乎是显而易见的方法,但它不起作用。而且我不知道如何更改代码。

标签: javascript html reactjs jsx


【解决方案1】:

您可以将渲染函数中的代码移动到getAllBooks,但您也应该将绑定移动到constructor

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    相关资源
    最近更新 更多