输入' undefined'不能分配给类型'(name:string)=>空隙'

时间:2018-02-09 23:15:32

标签: reactjs typescript

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

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

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

Menu.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

1 个答案:

答案 0 :(得分:0)

第42行的错误很清楚。

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

在界面中,您已将handleMenuClick定义为可选(通过在名称末尾添加&#34;?&#34;)。 cloneElement要求handleMenuClick不可选。

至于不处理tsx文件的codesandbox,请参阅this issue on github