如何处理 React 中的可重用组件?

How to handle reusable components in 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, FormGroup, 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