簡體   English   中英

如何收集用戶輸入以檢索 reactjs 中的數據?

[英]How to collect user input for retrieving data in reactjs?

我能夠獲取所有用戶並(通過按鈕單擊)通過 id 獲取特定用戶。 但我想不出一種從輸入中獲取用戶的方法。

有人可以建議如何實現嗎?

這是我的代碼:

import React, {Component} from 'react'

class App extends Component {

    constructor(props){
        super(props)
        this.onHandleUsers = this.onHandleUsers.bind(this)
        this.state = {
            isLoaded: false,
            users: []
        }
    }
    onHandleUsers() {
        fetch("http://localhost:3000/api/users")
        .then(res => res.json())
        .then(result => {
            this.setState({
                isLoaded: true,
                users: result
            })
        })
        .catch(e => console.log(e))
    }

    onHandleCurrentUsers(userId) {
        const data = {userId: userId}
        fetch("http://localhost:3000/api/user", {
            method: 'POST',
            headers: { "Content-Type": "application/json"},
            body: JSON.stringify(data)
        })
        .then(res => res.json())
        .then(result => {
            this.setState({
                isLoaded: false,
                currentUser: result
            })
        })
        .catch(e => console.log(e))
    }




    render() {
        const {currentUser} = this.state
        return (
            <div>

                <button onClick={this.onHandleUsers}>Gauti vartotojus</button>
                <ul>
                    {
                        this.state.isLoaded && this.state.users.map(item => {
                            return (
                                <li>name : {item.name} <br> 
                                </br>surname: {item.surname}</li>
                        )
                        })
                    }

                </ul>
                <button onClick ={e => this.onHandleCurrentUsers(1)}>get first user </button>
                <button onClick ={e => this.onHandleCurrentUsers(2)}>get second user </button>
                <div>
                    {
                        currentUser && <div>{currentUser.name} {currentUser.surname}</div>
                    }
                </div>

                <div>  </div>
        </div>
        )
    }
}

export default App

這相當簡單,您所要做的就是輸入一個處理所需用戶 ID 的輸入:

<input name='userId' onChange={this.handleUserChange} />

我們這樣定義 this.handleUserChange :

handleUserChange = (e) => {
  const {value} = e.target

  this.onHandleCurrentUsers(value)
}

基本上你將用戶的 id 傳遞給我們的輸入,它會改變當前用戶!

你好,這確實很有幫助,但我已經完成了這個,事情是這個它立即為當前用戶帶來輸入,我的問題是我必須點擊一個按鈕,然后才能獲得價值。 我正在嘗試像你一樣對 ref 做同樣的事情,但是在我輸入 atm 之后我無法帶回 ref ..

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM