如何解决如何在 React 中处理可重用组件?
我正在尝试制作一个可重用的输入组件。当数据输入时,我想在使用可重用输入组件的同一位置处理这些输入数据。不将其作为道具传递。
我收到一个错误
Uncaught TypeError: Cannot read property 'value' of undefined
谁能告诉我如何在这种情况下处理数据?
InputFieldWithImage.js
import React,{useState} from "react";
import { Form,FormGroup,Input } from 'reactstrap';
function InputFieldWithImage(props) {
const [inputType] = useState(props.type)
const [inputValue,setInputValue] = useState('')
function handleChange(event){
console.log("Input.js");
console.log(inputValue);
setInputValue(event.target.value);
if(props.onChange) props.onChange(inputValue)
}
return (
<>
<Input type={inputType} value={inputValue} name="input-form" onChange={handleChange} class="inputclass"/>
</>
);
}
export default InputFieldWithImage;
AddTicket.js
import { Row,Col } from 'reactstrap';
import { Form,Input } from 'reactstrap';
import ActionButton from './../../components/ButtonComponent';
import InputFieldWithImage from './../../components/InputField/InputFieldWithImage'
import { render } from 'react-dom';
import Reactquill from 'react-quill';
const AddTicket = (props) => {
const [assignee,setAssignee] = useState('');
const handleSubmit = (evt) => {
evt.preventDefault();
console.log('Assignee:' + assignee);
props.handleClose();
};
const test = () => {
console.log("text");
console.log('Assignee:' + assignee);
};
return (
<div className="popup-Box">
<div className="Box">
{/* <span className="close-icon" onClick={props.handleClose}>
x
</span> */}
<Form onSubmit={handleSubmit} style={{paddingLeft:30,paddingTop:50}}>
<Row style={{ paddingBottom: 50 }}>
<Col sm={11} xs={11} md={11}>
<h1>Add new ticket </h1>
</Col>
<Col onClick={props.handleClose} m={1} xs={1} md={1}>
<h1 className="close-icon">X </h1>
</Col>
</Row>
<FormGroup>
<Row style={{ marginBottom: '25px' }}>
<Col sm={2}>
<h4>Assignee</h4>
</Col>
<Col sm={2}>
<InputFieldWithImage value={assignee} onChange={(e) => setAssignee(e.target.value)} />
</Col>
</Row>
</FormGroup>
<Row>
<Col sm={2}></Col>
<Col>
<ActionButton text="Send" />
</Col>
</Row>
</Form>
</div>
</div>
);
};
export default AddTicket;
解决方法
您需要传递 event
而不是 inputValue
。因为有 input.target.value
。这就是为什么它给出错误
function handleChange(event) {
console.log("Input.js");
console.log(inputValue);
setInputValue(event.target.value);
if (props.onChange) props.onChange(event);
}
这是演示:https://codesandbox.io/s/hidden-tree-vr834?file=/src/App.js
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。