提问者:小点点

React Dumb component Typescript错误:元素不是JSX元素的构造函数,缺少属性“render”


"Dependencies":{
"typescript": "2.6.2"
"@types/react": "15.0.35",
"react": "15.6.1",
}

我试图制作一个“哑组件”,但typescript不接受我的函数定义。

(TS)JSX元素类型“()=

代码是不可接受的。

const Layout = (props: Invoice) => {
        const noResult = () => <p><em>Nothing found.</em></p>;

        const showResult = () => {
            return (
                <div className="col-sm-10" >
                    <div id="screenshotPlaceholder">
                        <div className="invoice-container">

                            <Header {...props} />

                            <div className="invoice-content">
                                <Content {...props } />
                            </div>

                        </div>
                    </div>
                </div>)
        };

        if (props === null)
            return noResult;
        return showResult;   
    }

如果我将最后两个返回值更改为下图所示的值,那么它将工作,但不太干净。

if (props === null)
    return <div>{noResult}</div>;
return <div>{showResult}</div>;

它似乎需要一个带有JSX内联的返回语句才能被识别为JSX组件?我的组件是不是太聪明了,不能使用哑组件语法?我认为这是相当优雅的,如果它的工作。


共2个答案

匿名用户

这不是smart的问题

您应该调用函数noResult

const Layout = (props: Invoice) => {
    const noResult = () => <p><em>Nothing found.</em></p>;

    const showResult = () => {
        return (
            <div className="col-sm-10" >
                <div id="screenshotPlaceholder">
                    <div className="invoice-container">

                        <Header {...props} />

                        <div className="invoice-content">
                            <Content {...props } />
                        </div>

                    </div>
                </div>
            </div>)
    };

    if (props === null)
        return noResult(); // ****** Note here
    return showResult();  // ****** And here
}

匿名用户

您不需要额外的函数包装:

const Layout = (props: Invoice) => {
  const noResult = (
    <p>
      <em>Nothing found.</em>
    </p>
  );

  const showResult = (
    <div className="col-sm-10">
      <div id="screenshotPlaceholder">
        <div className="invoice-container">
          <Header {...props} />

          <div className="invoice-content">
            <Content {...props} />
          </div>
        </div>
      </div>
    </div>
  );

  if (props === null)
    return noResult;
  return showResult;
};

或者,您可以不使用定义,而是调用函数:

  const noResult = () => <p><em>Nothing found.</em></p>;
  const showResult = () => {
  // ...
  };

  if (props === null)
    return noResult();
  return showResult();