问题描述
我在 React 中使用组件,但我没有在 Input 组件中使用函数。
我尝试在组件和 onChange 或 onKeyPress 上进行搜索,但它们没有显示我需要的内容。也许我搜索错了?我确实让组件 Button 工作,只是没有输入。
组件的代码很简单。
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;
我想用于组件 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 组件中工作。
有人有什么想法吗?我也试过使用 () 和 ''。
解决方法
因为您没有在 onChange
组件中使用道具 onKeyPress
和 Input
。只需像这样添加它:
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}
/>
);
}
,
React 无法知道应该将 onChange
和 onKeyPress
道具传递给 input
组件内的 Input
。
您必须明确地传递它们。
// Add them to your destructured props
function Input({inputText,onKeyPress}) {
return <input type='number'
onChange={onChange} // Pass them to the input
onKeyPress={onKeyPress} // Pass them to the input
placeholder={inputText}
className={styles.input}
/>
}
,
在组件 Input 中,您的返回应该是:<input></input>
因为 JSX 需要关闭标签。