【问题标题】:Updating props in Higher Order Components更新高阶组件中的道具
【发布时间】:2019-10-31 07:45:52
【问题描述】:

我正在尝试切换单选按钮并将道具更新为其设置的当前值。

我的Modal 组件正在渲染RadioButton 组件:

<RadioButton
  currentValue={destination}
  name={text.newOpp}
  onChange={onClick}
  value={text.newOpp}
  labelText={text.newOpp}
/>

onClick 函数正在被传入,此时看起来像这样:

export const onClick = ({ destination }) => ({ target }) => {
  let copyDestination = {};
  copyDestination.destination = target.name;
  destination = copyDestination;
  // this doesn't really do anything
};

export default compose(
  ...
  ...
  withProps({ destination: '' }),
  ...
);

RadioButton 使用recompose 进行了增强,并将此函数作为道具传递:

export const checked = ({ currentValue, value }) => {
  return currentValue === value;
};

这就是组件的输入部分的样子:

    <input
      checked={checked}
      className={styles.input}
      id={uniqueIdForHTML}
      name={name}
      onChange={onChange}
      type="radio"
      value={value}
    />

本质上,这应该起作用的方式是,当我单击单选按钮时,我将其 currentValue 属性更新为 target.name 等于的任何值。但我不完全确定如何更新道具,因为它们不应该直接改变。

【问题讨论】:

  • 为什么在有钩子的时候使用recompose?你只是想更新 HOC 的 props 吗?
  • 我遵守这个项目的编码标准。它大约有一年的历史,所以一切都是用 recompose 构建的。
  • currentValue 属性从 destination 获取价值 - 更新 destination - 可能通过呈现 &lt;RadioButton/&gt; 的父/组件中的 setState - 阅读有关“提升状态”的文档

标签: javascript reactjs recompose


【解决方案1】:

我最终使用withStateHandler 创建状态并更新它,我还将onClick 函数的名称更改为setDestination,这样更有意义。

export const setDestination = ({ destination }) => ({ target }) => ({
  destination: target.name,
});

export default compose(
  setDisplayName('OpportunityPageFeatures/CopyDestinationModal'),
  withUniqueIDForHTML,
  withStateHandlers({ destination: '' }, { setDestination }),
  consoleLogProps,
);

【讨论】:

    猜你喜欢
    • 2021-04-14
    • 2019-03-26
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    相关资源
    最近更新 更多