父组件的表单校验触发子组件的输入框
时间: 2024-02-28 20:49:53 浏览: 33
在React中,父组件可以通过props将表单校验的状态传递给子组件的输入框。以下是一个示例:
父组件:
```jsx
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const [inputValue, setInputValue] = useState('');
const [isInputValid, setIsInputValid] = useState(true);
const handleInputChange = (e) => {
setInputValue(e.target.value);
};
const handleFormSubmit = (e) => {
e.preventDefault();
// 进行表单校验逻辑
if (inputValue === '') {
setIsInputValid(false);
} else {
setIsInputValid(true);
}
};
return (
<div>
<form onSubmit={handleFormSubmit}>
<input
type="text"
value={inputValue}
onChange={handleInputChange}
className={isInputValid ? '' : 'invalid'}
/>
<button type="submit">提交</button>
</form>
<ChildComponent isInputValid={isInputValid} />
</div>
);
};
export default ParentComponent;
```
子组件:
```jsx
import React from 'react';
import PropTypes from 'prop-types';
const ChildComponent = ({ isInputValid }) => {
return (
<div>
{isInputValid ? (
<p>输入框校验通过</p>
) : (
<p>输入框校验未通过</p>
)}
</div>
);
};
ChildComponent.propTypes = {
isInputValid: PropTypes.bool.isRequired,
};
export default ChildComponent;```
在上述示例中,父组件通过useState来管理输入框的值和校验状态。当表单提交时,父组件根据输入框的值进行校验,并将校验状态通过props传递给子组件。子组件根据接收到的校验状态来展示不同的内容。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)