【问题标题】:React function in a component组件中的反应函数
【发布时间】:2021-09-29 20:22:30
【问题描述】:

我正在使用组件在 React 中工作,但我没有让函数在 Input 组件中工作。

我尝试在组件和 onChange 或 onKeyPress 上进行搜索,但它们没有显示我需要的内容。也许我搜索错了?我确实让组件按钮工作,只是没有输入。

组件的代码很简单。

import React from 'react';
import styles from './Input.module.css';

function Input({inputText}) {
    return <input type='number'
                  placeholder={inputText}
                  className={styles.input}
    />
}

export default Input;

我想用于组件输入的完整代码如下。

import React, {useState} from 'react';
import styles from './Food.module.css';
import axios from 'axios';
import Nutrients from '../../components/nutrients/Nutrients'
import {ReactComponent as LoadingIcon} from '../../assets/loading.svg'
import Button from "../../components/button/Button";
import Input from "../../components/input/Input";

function Food() {
    const [food, setFood] = useState(null);
    const [calories, setCalories] = useState('');
    const [disabled, setDisabled] = useState(false);
    const [error, setError] = useState('');
    const [loading, toggleLoading] = useState('');

    async function foodData() {
        setError('');
        toggleLoading('true')

        try {
            const result = await axios.get(`https://api.spoonacular.com/mealplanner/generate?apiKey=${process.env.REACT_APP_API_KEY}&timeFrame=day&targetCalories=${calories}`);
            setFood(result.data);
        } catch (error) {
            setError('Oops... something went wrong. Please try again.');
            console.log('Something went wrong while retrieving the data.', error);
        }
        toggleLoading(false);
    }

    function handleChange(e) {
        setCalories(e.target.value);
    }

    function handleKeyPress(e) {
        if (e.key === 'Enter') {
            if (disabled) {
                return;
            }
            foodData();
            setDisabled(true);
        }
    }

    return (
        <>
            {error && <p className={styles.error}>{error}</p>}
            <div>
                <section className={styles.food}>

                    <Input
                        inputText='Enter caloriessss'
                        onChange= {handleChange}
                        onKeyPress={handleKeyPress}
                    />
                    <Button
                        onClick={() => {
                            foodData();
                            setDisabled(true);
                        }}
                        buttonText='Click for your daily meals'
                    />
                </section>
                {loading && <LoadingIcon className={styles.loader}/>}
                {food && <Nutrients mealsData={food}/>}
            </div>
        </>
    );
}

export default Food;

我想要的是让 onChange 和 onKeyPress 这两个函数在 Input 组件中工作。

有人有什么想法吗?我也尝试使用 () 和 ''。

【问题讨论】:

    标签: reactjs function components onchange onkeypress


    【解决方案1】:

    React 无法知道应该将 onChangeonKeyPress 属性传递给 input 内部的 Input 组件。

    您必须明确地传递它们。

    // Add them to your destructured props
    function Input({inputText, onChange, onKeyPress}) {
        return <input type='number'
          onChange={onChange} // Pass them to the input
          onKeyPress={onKeyPress} // Pass them to the input
          placeholder={inputText}
          className={styles.input}
        />
    }
    

    【讨论】:

      【解决方案2】:

      在组件输入中,您的返回应该是:&lt;input&gt;&lt;/input&gt; 因为 JSX 需要封闭标签。

      【讨论】:

      • 他们使用的是自闭标签,所以不需要。
      【解决方案3】:

      因为你没有在Input 组件中使用道具onChangeonKeyPress 。只需像这样添加它:

      function Input({ inputText, onChange, onKeyPress }) {
        return (
          <input
            type="number"
            placeholder={inputText}
            className={styles.input}
            onChange={onChange}
            onKeyPress={onKeyPress}
          />
        );
      }
      

      或更短的方式:

      function Input({ inputText, ...props }) {
        return (
          <input
            type="number"
            placeholder={inputText}
            className={styles.input}
            {...props}
          />
        );
      }
      

      【讨论】:

      • 是的,就是这样!我以为我已经尝试过了,但我想我做错了什么。谢谢!
      猜你喜欢
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      • 2022-11-07
      • 2017-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多