我是新来的反应。我的问题is....There是独立功能组件中的输入字段和按钮。当用户在输入字段中输入数据并单击按钮时,输入的数据应该显示在控制台中。有App.js,它是父组件,还有Input.js(子组件)和Submit.js(子组件)。Submit.js有按钮。我们进口Input.js和Submit.js在App.js.中。
我们应该验证输入数据并单击submit按钮,如果数据格式不正确,则显示错误。其他明智的做法是,在控制台中以json格式管理数据.。
我希望你能理解逻辑。请把密码发过来。我试过思考,但失败了。请帮我弄清楚密码。谢谢
发布于 2022-02-17 13:50:02
在App.js中
import { useState } from "react";
import Input from "./Input";
import Submit from "./Submit";
export default function App() {
const [value, setValue] = useState("");
const handleChange = (event) => {
setValue(event.target.value);
};
const handleSubmit = () => {
console.log(value); // do validation with `value`
console.log(JSON.stringify({ error: "" })); // console JSON data on error
};
return (
<div>
<Input value={value} handleChange={handleChange} />
<Submit handleSubmit={handleSubmit} />
</div>
);
}Input.js
export default function Input({ value, handleChange }) {
return <input type="text" value={value} onChange={handleChange} />;
}Submit.js
export default function Submit({ handleSubmit }) {
return (
<button type="submit" onClick={handleSubmit}>
Submit
</button>
);
}发布于 2022-02-17 13:29:36
最简单的解决方案是在app.js中创建一个状态,并给出输入值和onChange支持,同时为按钮提供状态值的提交函数。
发布于 2022-02-17 14:46:37
import React, { useState } from 'react';
import TextInput from './TextInput';
import SubmitButton from './SubmitButton';
const App = () => {
const [inputVal, setInputVal] = useState(null);
const [OutPut, setOutPut] = useState({ error: false, errorText:'',correctVal: '' });
const checkInput = () => {
if (Number.isInteger(+inputVal) === false)return setOutPut({ ...OutPut,
error: true, errorText: 'Input field accept only numbers' });
//Add API call after validating at below else condition
else setOutPut({ ...OutPut, error: false, correctVal: inputVal });
}};
return (
<div>
<TextInput setInputVal={setInputVal} />
<SubmitButton checkInput={checkInput} />
{OutPut.error === true ? (
<h3 style={{ color: 'red' }}>{OutPut.errorText}</h3>
) : (OutPut.error===false && OutPut.correctVal !==''?(
<h3 style={{ color: 'blue' }}>Your input is : {OutPut.correctVal}</h3>
):'')}
</div>
);
};
export default App;2.Button
import React from 'react';
const SubmitButton = ({ checkInput }) => {return <button type='button' onClick={() => checkInput()}>Submit</button>};
export default SubmitButton;3.Input.js
import React from 'react';
const TextInput = ({ setInputVal }) => {
return (
<input
type='text'
placeholder='Type anything here to see if your input is number'
onChange={(e) => setInputVal(e.target.value)}
/>
);
};
export default TextInput;您可以检查沙箱链接上的输出:https://codesandbox.io/s/bold-ishizaka-ktzfu3?file=/src/App.js
https://stackoverflow.com/questions/71158798
复制相似问题