【问题标题】:Passing existing prop to component and appending将现有道具传递给组件并附加
【发布时间】:2020-02-29 00:24:31
【问题描述】:
const LNTextField = props => {
  const classes = useStylesReddit();
  return (
    <TextField
      variant="filled"
      InputProps={{ classes, disableUnderline: true }}
      {...props}
    />
  );
};

这是一个功能组件 假设我想在使用这个组件时向 InputProps 对象添加一些东西,同时在功能组件中维护 InputProps 对象 我怎样才能做到这一点? 例如;

<LNTextField
                InputProps={{
                  endAdornment: (
                    <InputAdornment
                      className={styles.optionalAppendedText}
                      position="end"
                    >
                      Optional
                    </InputAdornment>
                  )
                }}/>

现在它覆盖了组件中的 InputProps

TIA

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    如何为InputProps 使用与父级不同的道具名称?假设,来自父级的 InputProps 以InputPropsParent 命名。而且,您可以尝试这样做:

    const LNTextField = props => {
      const classes = useStylesReddit();
      return (
        <TextField
          variant="filled"
          InputProps={{ ...props.InputPropsParent, classes, disableUnderline: true }}
          {...props}
        />
      );
    };
    

    更新

    作为 OP 评论,上面的代码不起作用。下面的代码是工作代码,尽管这是否是最好的方法。

    const LNTextField = props => {
          const classes = useStylesReddit();
          return (
            <TextField
              variant="filled"
              InputProps={{ ...props.inputpropsparent, classes, disableUnderline: true }}
              {...props}
            />
          );
        };
    

    【讨论】:

    • index.js:1375 警告:React 无法识别 DOM 元素上的 InputPropsParent 属性。如果您有意希望它作为自定义属性出现在 DOM 中,请将其拼写为小写 inputpropsparent。如果您不小心从父组件中传递了它,请将其从 DOM 元素中移除。
    • 它以小写字母工作,这是最好的方法吗?如果不使用不同的道具名称,就没有办法只附加 InputProps 吗?
    • 用camelCased怎么样?它有效吗?如果可行,我更喜欢使用 camelCased。 Idk,您是否尝试使用相同的道具名称?并将...props.InputPropsParent 替换为...props.InputProps?
    • 抱歉,我不知道解决您问题的其他方法
    猜你喜欢
    • 2017-07-02
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 2019-02-26
    • 1970-01-01
    • 2020-01-17
    相关资源
    最近更新 更多