Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 无法实例化可能返回null的无状态FunctionalComponent_Reactjs_Typescript2.0 - Fatal编程技术网

Reactjs 无法实例化可能返回null的无状态FunctionalComponent

Reactjs 无法实例化可能返回null的无状态FunctionalComponent,reactjs,typescript2.0,Reactjs,Typescript2.0,我定义了一个组件: interface Role { name: string; description: string; } interface BPRolesProps extends React.Props<null> { roles: Role[]; } const BPRoles = ({ roles }: BPRolesProps) => { if (!roles.length) { return null; } return (

我定义了一个组件:

interface Role {
  name: string;
  description: string;
}

interface BPRolesProps extends React.Props<null> {
  roles: Role[];
}

const BPRoles = ({ roles }: BPRolesProps) => {
  if (!roles.length) {
    return null;
  }
  return (
    <div>
      {roles.map(r => <div key={r.name}><span title={r.description}>{r.name}</span></div>)}
    </div>
  );
};

无状态纯函数组件不能以这种方式呈现。相反,您需要一个使用标准React.createClass或es6版本构建的容器组件,它将呈现无状态组件,并且是ReactDOM.render方法使用的组件。看

ReactDOM.render还需要一个dom元素作为第二个参数。
render(,null)您需要一个有效的html元素作为第二个参数,您传递的是null,它不是DOM元素

有一个问题与此问题相关

目前,此技巧可作为一种变通方法:

const BPRoles = ({ roles }: BPRolesProps) => {
  if (!roles.length) {
    return null!; // <= never is assignable to anything, so the return type will be Element
  }
  return (
    <div>
      {roles.map(r => <div key={r.name}><span title={r.description}>{r.name}</span></div>)}
    </div>
  );
};
constbproles=({roles}:BPRolesProps)=>{
如果(!roles.length){
返回null!;//{r.name})
);
};

谢谢你的回答。但是我使用了
render
来制作一个工作示例。问题是代码是有效的react代码,但不是有效的Typescript代码!我提出了一个问题
error TS2605: JSX element type 'Element | null' is not a constructor function for JSX elements.
  Type 'null' is not assignable to type 'ElementClass'.
const BPRoles = ({ roles }: BPRolesProps) => {
  if (!roles.length) {
    return null!; // <= never is assignable to anything, so the return type will be Element
  }
  return (
    <div>
      {roles.map(r => <div key={r.name}><span title={r.description}>{r.name}</span></div>)}
    </div>
  );
};