首页 > 解决方案 > 从 inputComponent 捕获 onChange 事件传递给 OutlinedInput,Material UI

问题描述

我正在尝试将 OutlinedInput 与 KeyboardDatePicker 一起使用,两者都来自 Material UI。我将 DatePicker 作为输入组件传递给 Material UI 的“OutlinedInput”组件。我想知道如何从我传递的 inputComponent 中获取日期。

使用以下代码,我收到“_onChange 不是函数”错误。



    const handleInputChange = (event) => {
        if (event.target.name === "deliveryDate") {
            temp.deliveryDate = event.target.value;
        }
    }


    function datepicker() {
        return <MuiPickersUtilsProvider utils={DateFnsUtils}>
               <KeyboardDatePicker
                    name="deliveryDate"
                    format="MM/dd/yyyy"
                    value={projectDetails.deliveryDate}
                    onChange={props.handleInputChange} />  //not sure if this is how I should write it
               </MuiPickersUtilsProvider>;
    }


return(
    <OutlinedTextBox
          name="deliveryDate"
          id="deliveryDate"
          maxlength={20}
          onChange={handleInputChange}
          inputComponent = {datepicker}   //passing the KeyboardDatePicker as input component
          inputLabel="Delivery Date" />
      )

下面是我的 OutlinedTextBox 组件。它返回

                    <OutlinedInput
                        name={props.name}
                        inputProps={{
                            maxLength: props.maxlength?props.maxlength:100,
                          }}
                        onChange={props.handleInputChange}
                        {...props}
                    />

如何捕获 inputComponent 属性的 onChange 函数。

标签: reactjsmaterial-ui

解决方案


更新

根据您在评论中所说的,您实际上需要做的就是编辑您的日期选择器组件。您不需要直接传入值、onChange 或名称,因为它们在您使用inputComponent={datepicker}. 所以你需要做的就是声明props并将它们全部传播到KeyboardDatePicker中。

const DatePicker = (props) => {
  return (
    <MuiPickersUtilsProvider utils={DateFnsUtils}>
      <KeyboardDatePicker
        format="MM/dd/yyyy"
        {...props}
      />
    </MuiPickersUtilsProvider>
  );
};


原始答案

您可以将inputVariant="outlined"属性添加到 KeyboardDatePicker,因为这将使其概述。然后,您实际上根本不需要使用 OutlinedInput 组件。

<KeyboardDatePicker
    name="deliveryDate"
    format="MM/dd/yyyy"
    value={projectDetails.deliveryDate}
    onChange={props.handleInputChange}
    inputVariant="outlined
/>


推荐阅读