【问题标题】:Props are undefined in hoisted renderInput function (React)提升的 renderInput 函数中未定义道具 (React)
【发布时间】:2020-11-22 03:43:50
【问题描述】:

我有一个链接到父主页的功能 SearchBar 子组件。我从父组件传递了 id 和 label 的 props。子组件将道具 id 和标签读取为“未定义”。我对另一个下拉组件有完全相同的代码,它可以工作。我的猜测是,这可能是因为我将道具传递给提升的(功能组件主体上方)renderInput 函数?你可以将道具传递给提升的辅助函数吗?我也在使用 Redux Form,我不确定它是否会使事情复杂化。 Input 是 Redux Form 的一个 prop,工作正常。这是我的代码:

//helper render function hoisted to prevent re-render of searchbar with every key stroke
const renderInput = ({ id, label input }) => {
  return (
    <div className="container position-relative" id={id}>
      {label}

      <input
        {...input}
        type="text"
        placeholder="Search..."
        className="py-4 px-5 border rounded-sm form-control"
      />
    </div>
  );
};

const SearchBar = ({ handleSubmit, submitSearch }) => {
    
    const onSubmit = (formValues, dispatch) => {
        submitSearch(formValues); //calls search action creator
        dispatch(reset("SearchBar")); //clears search form after submission 
    }
    
    return (
      <form onSubmit={handleSubmit(onSubmit)}>
        <Field
          name="search"
          component={renderInput}
        />
      </form>
    ); 
}

【问题讨论】:

  • 你不能传递除 inputmeta 之外的属性,它们在 Redux 表单中定义(参见 docs)。但是你可以指定你从哪里得到idlabel,所以也许我们可以想出一个解决方案。
  • 嗨@rostyslav!谢谢,可能是这个问题。 id 和 label 属性来自 SearchBar 父级(我正在定义和创建它们,就像您在普通 React 组件中所做的那样:)。我不能将自己创建的 React 道具传递给 Redux From 组件吗?我该怎么做呢?非常感谢,在这个问题上卡了几个小时。
  • 您的搜索栏似乎只分解了来自 props const SearchBar = ({ handleSubmit, submitSearch }) 的两个参数。 id 和 label 不会被分解。应该是 const SearchBar = ({ id, label, handleSubmit, submitSearch })
  • 但我仍然认为您的示例中缺少一些代码
  • 您好,感谢您的帮助。我想到了。我必须将 id 和 label 的自定义道具传递给 Redux Form 中的 组件。这就是缺少的东西。我将在下面的答案中发布我的工作代码。

标签: javascript reactjs


【解决方案1】:

这是工作代码,如果其他人遇到同样的问题。您必须将 id 和 label 的自定义 props 传递给 Redux Form 中的 Field 组件,以便 Redux Form 组件读取它。

<Field name="search" component={renderInput} id={id} label={label} />

【讨论】:

    猜你喜欢
    • 2017-04-02
    • 2018-11-12
    • 2016-11-08
    • 2018-04-18
    • 1970-01-01
    • 2022-06-30
    • 2018-11-05
    • 2022-07-06
    • 1970-01-01
    相关资源
    最近更新 更多