【问题标题】:Type 'undefined' is not assignable to type '(name: string) => void'类型“未定义”不可分配给类型“(名称:字符串)=> void”
【发布时间】:2018-07-20 19:02:26
【问题描述】:

我正在尝试学习 Typescript,这是我创建的 Menu 组件,但是我无法弄清楚它们在 menu.tsx 行中显示的错误。 42

这是return React.cloneElement(child, newProps);这一行

如果有人能指出我将不胜感激

菜单.tsx

export interface MenuProps {
  defaultActiveItem?: string;
  className?: string;
  onClick?: (name: string) => never;
}

class Menu extends Component<MenuProps> {
  static Item = MenuItem;
  state = {
    selected: this.props.defaultActiveItem
  };

  handleMenuClick = (name: string) => {
    this.setState({
      selected: name
    });
    if (this.props.onClick) {
      this.props.onClick(name);
    }
  };

  render() {
    const {
      children,
      className,
      onClick,
      defaultActiveItem,
      ...rest
    } = this.props;
    const computedClasses = classnames(className);
    const childrenWithNewProps = React.Children.map(
      children,
      (child: React.ReactElement<ItemProps>) => {
        const newProps = {
          handleMenuClick: this.handleMenuClick,
          active: this.state.selected === child.props.name
        };
        return React.cloneElement(child, newProps);
      }
    );
    return (
      <ul className={computedClasses} {...rest}>
        {childrenWithNewProps}
      </ul>
    );
  }
}

MenuItem.tsx

export interface ItemProps {
  handleMenuClick?: (name: string) => void;
  name: string;
  active?: boolean;
  children?: any;
}

const defaultProps = {
  active: false
};

const MenuItem: React.StatelessComponent<ItemProps> = ({
  handleMenuClick,
  name,
  active,
  children,
  ...rest
}) => {
  const computedClasses = classnames(styles.menuItem, {
    [styles.selected]: active
  });

  return (
    <li
      className={computedClasses}
      onClick={() => handleMenuClick && handleMenuClick(name)}
      {...rest}
    >
      {children}
    </li>
  );
};

MenuItem.defaultProps = defaultProps;
export default MenuItem;

https://codesandbox.io/s/n4lvv0m2vl

【问题讨论】:

  • 能否请您也发布在问题中引发错误的代码?
  • 当然,我希望拥有一个编辑过的代码沙箱会更好

标签: reactjs typescript


【解决方案1】:

第42行的错误很清楚。

export interface ItemProps {
  handleMenuClick?: (name: string) => void;
  name: string;
  active?: boolean;
  children?: any;
}

在界面中,您已将handleMenuClick 定义为可选(通过在名称末尾添加“?”)。 cloneElement 要求 handleMenuClick 不是可选的。

关于不处理 tsx 文件的代码沙盒,请参阅this issue on github

【讨论】:

  • 知道了!你有什么建议?我有两个想法,第一个。为 newProps 创建一个新类型。第二次使用相同的ItemProp 界面,但我必须手动传播原始道具,cloneElement 已经这样做了
猜你喜欢
  • 2022-01-07
  • 2021-09-14
  • 2021-08-19
  • 2017-10-01
  • 2021-10-19
  • 2018-06-24
  • 1970-01-01
  • 2021-04-06
  • 2018-01-04
相关资源
最近更新 更多