【问题标题】:How to get the value of user input field using ReactJS?如何使用 ReactJS 获取用户输入字段的值?
【发布时间】:2020-07-29 22:54:41
【问题描述】:

我正在尝试根据用户输入字段获取 api 数据。如何获取这些数据的值?

我的 api 端点像这样 "http://localhost:8000/api/p_list?search=" 。每当用户输入值时,端点就像这样“http://localhost:8000/api/p_list?search=01”这里是输入字段值是“01”。我想得到结果的值。

我可能是 reactjs 的新手。我在下面尝试了类似的东西,但这是我要获取的静态 API url。我不确定如何根据用户输入字段获取动态 url。

如果有人能帮助我解决我想要解决的问题,那就太好了。非常感谢您。


./src/productList.js

import React, {Component} from "react";
import Contacts from './productListHook.js';


export default class App  extends Component{

   state = {
       contacts: []
   }

   componentDidMount() {
       fetch('http://localhost:8000/api/p_list?search=')
       .then(res => res.json())
       .then((data) => {
         this.setState({ contacts: data })
       })
       .catch(console.log)
     }

   render(){
   return(

       <Contacts contacts={this.state.contacts} />
   )
}
}


./src/ProductListHook.js


import React from 'react'

    const Contacts = ({ contacts }) => {
      return (

        <section class="product_list section_padding">
        <div class="container">
            <div class="row">
                <div class="col-md-3">
                    <div class="product_sidebar">
                        <div class="single_sedebar">
                            <form action="#">
                                <input type="text" name="#" placeholder="Search keyword"/>
                                <i class="ti-search"></i>
                            </form>
                        </div>
                    </div>
                </div>
                <div class="col-sm-9">
                    <div class="product_list">
                        <div class="row">

                        {contacts.map((contact) => (

                            <div class="col-lg-3 col-md-9">
                                <div class="single_product_item">
                                    <img src={contact.image} alt="" class="img-fluid" />
                                    <h3> <a href={contact.url}>{contact.title}</a> </h3>
                                    <p>From ${contact.price}</p>
                                </div>
                            </div>

                            ))}

                        </div>
                        <div class="load_more_btn text-center">
                            <a href="#" class="btn_3">Load More</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        </section>

      )
    };

export default Contacts

【问题讨论】:

  • 您需要将输入值传递给请求 url 吗?
  • 您可以创建一个包含用户输入的状态。然后它将被存储并可供您调用。
  • 我要解决的这个答案是“therichpost.com/get-input-field-value-button-click-reactjs”吗? @happyZZR1400
  • 我可能是 reactjs 的新手,我不知道该怎么做。你能在沙箱环境中运行这段代码吗? @TheoWckr

标签: javascript reactjs react-redux


【解决方案1】:

嗨,请检查这个完整的示例:它使用文本框从用户那里获取用户 ID,然后单击按钮后,它会使用该用户 ID 调用 api 并获取该用户的所有帖子。之后它会在屏幕上显示所有帖子标题。

import React, {useEffect, useState} from "react";
import axios from 'axios';

function PostListPageByUser() {
    const [posts, setPost] = useState([]);
    const [userId, setUserId] = useState([]);
    let signal = axios.CancelToken.source();

    function handleChange(event) {
        setUserId(event.target.value);
    }

    function handleClick(event) {
        axios.get(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`, {
            cancelToken: signal.token,
        })
            .then(res => {
                const posts = res.data;
                setPost(posts);
            }).catch(err => {
            console.log(err);
        });
    }
    return (
        <React.Fragment>
            <span>Enter User Id</span>
            <input type="text" onChange={handleChange}/>
            <button onClick={handleClick}>Get Posts By User</button>
            <ul>
                {
                    posts.map(post => <li key={post.id}>{post.title}</li>)
                }
            </ul>
        </React.Fragment>
    );
}
export default PostListPageByUser;

根据您对我的回答的评论,我在表单提交中添加了这个示例:

import React, {useEffect, useState} from "react";
import axios from 'axios';

function PostListPageByUser() {
    const [posts, setPost] = useState([]);
    const [userId, setUserId] = useState([]);
    let signal = axios.CancelToken.source();

    function handleChange(event) {
        setUserId(event.target.value);
    }

    function handleSubmit(event) {
        event.preventDefault();
        axios.get(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`, {
            cancelToken: signal.token,
        })
            .then(res => {
                const posts = res.data;
                setPost(posts);
            }).catch(err => {
            console.log(err);
        });
    }

    return (
        <form onSubmit={handleSubmit}>
            <span>Enter User Id</span>
            <input type="text" onChange={handleChange}/>
            <button type="submit">Get Posts By User</button>
            <ul>
                {
                    posts.map(post => <li key={post.id}>{post.title}</li>)
                }
            </ul>
        </form>
    );
}

export default PostListPageByUser;

【讨论】:

  • 好的!如果我有
    ,那么我应该在动作中传递什么?
  • 你好表单,你应该使用
    并且按钮类型将被提交如下:
  • 嗨,它不会在搜索字段中输入任何输入,而是将“提交”作为参数。
  • 嗨,我添加了另一个可以正常工作的示例。请检查一下。
  • 为什么在最后一节结束了“”标签?您可以将“”标签放在“”标签的末尾。这会导致任何错误吗?
【解决方案2】:

您的 Contacts 组件有输入,但 API 调用是在其父 App 组件中进行的。

您需要做的是将另一个prop 传递给Contacts,这是一个函数,每次Contacts 中的输入状态发生变化时都会调用该函数。

例子:

class App extends React.Component {
  ...

  search(inputValue){
    fetch(`http://localhost:8000/api/p_list?search=${inputValue}`)
    .then(res => res.json())
    .then((data) => {
      this.setState({ contacts: data })
    })
    .catch(console.log)
  }

  render() {
    <Contacts contacts={this.state.contacts} onSearch={search}/>
  }

现在在Contacts 组件内:

const Contacts = ({contacts, onSearch}) => {
  const [search, setSearch] = useState('');
  return (
    ...
    <input onChange={
           (e) => {
            setSearch(search);
            onSearch(e.currentTarget.value);
           }
         } value={search} .../>
    ...
   )
}

我刚刚编写了概念代码以使其工作,它缺少bind 和有关您项目的其他具体实现。

我强烈建议您在 onSearch 函数中实现一个逻辑来延迟 API 调用,因为它将在输入中输入的新字母中触发。这可能会使 api 过载。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-07
    • 2015-11-15
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 2012-07-18
    相关资源
    最近更新 更多