首页 > 解决方案 > 将函数作为道具传递

问题描述

尝试将 {} 放在作为道具传递的函数周围时,我遇到了“渲染中没有返回任何内容”问题。我想也许我把它们放在了错误的地方。

我应该将 {} 放在此代码的什么位置?

const WhiteAdvantageTags = props => {
  props.whiteAdvantageTags.map(function (name1, index1) {
    return (
      <Typography
        style={{
          lineHeight: '2',
          marginLeft: '0px',
          padding: '0',
        }}
      >
        <Link
          href="#"
          onClick={event => {
            props.popupInstruction(name1, 'White');
          }}
          onMouseOver={event => {
            props.highlightSquares(name1, 'White');
          }}
          onMouseLeave={event =>
            props.board.current.removeMarkers(undefined, undefined)
          }
          variant="body2"
        >
          - {name1}
        </Link>
      </Typography>
    );
  });
};

标签: reactjs

解决方案


为了使用 {} 大括号来包装您的函数,您需要确保从该函数显式返回某些内容。在这个例子中,用大括号实现它的正确方法是:

const WhiteAdvantageTags = props => {
  return props.whiteAdvantageTags.map(function (name1, index1) { // added return statement
    return (
      <Typography
        style={{
          lineHeight: '2',
          marginLeft: '0px',
          padding: '0',
        }}
      >
        <Link
          href="#"
          onClick={event => {
            props.popupInstruction(name1, 'White');
          }}
          onMouseOver={event => {
            props.highlightSquares(name1, 'White');
          }}
          onMouseLeave={event =>
            props.board.current.removeMarkers(undefined, undefined)
          }
          variant="body2"
        >
          - {name1}
        </Link>
      </Typography>
    );
  });
};

但是,由于该函数只是返回此值,因此您可以直接返回它:

const WhiteAdvantageTags = props => props.whiteAdvantageTags.map(function (name1, index1) {
    return (
      <Typography
        style={{
          lineHeight: '2',
          marginLeft: '0px',
          padding: '0',
        }}
      >
        <Link
          href="#"
          onClick={event => {
            props.popupInstruction(name1, 'White');
          }}
          onMouseOver={event => {
            props.highlightSquares(name1, 'White');
          }}
          onMouseLeave={event =>
            props.board.current.removeMarkers(undefined, undefined)
          }
          variant="body2"
        >
          - {name1}
        </Link>
      </Typography>
    );
  });

推荐阅读