React TypeScript:地图内的onClick

时间:2019-12-20 14:10:17

标签: reactjs typescript

在地图内进行onClick时出现的错误是...

Type 'void' is not assignable to type '((event: MouseEvent<HTMLDivElement, MouseEvent>) => void) | undefined'.ts(2322)
index.d.ts(1348, 9): The expected type comes from property 'onClick' which is declared here on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'

向下滚动到渲染部分,以查看地图中的onClick ... 也许有一种更好的方法来重定向用户,这也解决了这个问题?

import React, { useContext, useEffect, useState } from 'react';
import { Global } from '../globalState';

const Followers: React.FC = () => {
  const { global } = useContext(Global);
  const username = window.location.pathname.substr(1);

  interface Follower {
    fullName: string;
    username: string;
    avatarId?: string;
  }

  const [state, setState] = useState({
    followers: [],
  });
  const { followers } = state;

  useEffect(() => {
    async function getFollowers() {
      const response = await fetch(`${global.env.apiUrl}/user/followers`, {
        body: JSON.stringify({ username }),
        headers: {
          // prettier-ignore
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        method: 'POST',
      });
      const content = await response.json();
      if (response.status === 200) {
        setState((prev) => ({ ...prev, followers: content.followers }));
      }
    }
    if (username) {
      getFollowers();
    }
  }, [username, global.env.apiUrl]);

  const gotoUser = (user: string) => { // <------------- onClick calls this function
    window.location.href = (`/${user}`);
  };
  const getAvatar = (fullName: string) => {
    return (
      global.env.imgUrl +
      'initials/' +
      fullName.charAt(0).toLowerCase() +
      '.png'
    );
  };
  return (
    <div className='followers'>
      <h2>Followers</h2>

      {followers.map((person: Follower) => ( // <------------- Map starts
        <div className='followers--grid'>
          <div onClick={gotoUser(person.username)}> // <------------- onClick 
            {person.avatarId && (
              <img
                src={global.env.imgUrl + person.avatarId}
                className='followers--image'
              />
            )}
            {!person.avatarId && (
              <img
                src={getAvatar(person.fullName)}
                className='followers--image'
              />
            )}
          </div>
          <div>
            <p className='followers--name'>{person.fullName}</p>
            <p className='followers--username'>@{person.username} </p>
          </div>
          <div className='followers--follow'>+ Follow</div>
        </div>
      ))}
    </div>
  );
};

export { Followers };

1 个答案:

答案 0 :(得分:2)

尝试一下:

<div onClick={()=>gotoUser(person.username)}> 

onClick需要一个功能。 gotoUser()不返回任何内容(未定义)。这就是为什么您会遇到错误。创建一个新的箭头函数,或者使用不带括号的gotoUser来传递函数本身而不是返回值。