javascript - 编写分支渲染的 ReactJS 组件

标签 javascript reactjs

我有一个 H1 组件:

<H1 importance={importance}>foo</H1>

我希望 H1 的呈现取决于 importance 属性。

所以我尝试了:

import styled from 'styled-components';

const Default = styled.h1`
  font-size: 1.2em;
`;

const High = styled.h1`
  font-size: 2.2em;
`;

function H1({ importance }) {
  return importance === 'HIGH' ? 
    (<High props={...props}/>) : 
      (<Default props={...props}/>);
}

export default H1;

但是我得到:

A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

这是为什么?

我还希望内容(此处为“foo”)在子组件内呈现。我怎样才能做到这一点?

最佳答案

A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

我已经检查了我的项目,它工作正常......你的错误可能在其他地方......


Also I want the contents ("foo" here) to be rendered inside the child component. How can I achieve this?

function H1({ importance, children }) {

  return importance === 'HIGH' 
    ? (<High>{children}</High>) 
    : (<Default>{children}</Default>);
}

更新

如果你想把所有的 Prop 传递给 children ,那么你可以在 Prop 上使用Object Spread Operator:Spread Attributes

function H1(props) {

  return importance === 'HIGH' 
    ? (<High {...props} />) 
    : (<Default {...props} />)
  ;
}

关于javascript - 编写分支渲染的 ReactJS 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45462917/

相关文章:

javascript - 如何从方法 JS 访问类变量

javascript - 如何从填充的字段中删除 key ?

javascript - 如何覆盖listItem图标工具提示?

javascript - Angular ngStyle 带有 ngIf 的动态样式元素

javascript - 按 React Native Elements UI Toolkit 中的按钮转到 Web URL

node.js - 服务器端 NodeJS - 需要客户端 Windows ID

javascript - map函数中setState的使用方法

javascript - 渲染 react 组件时出错(对象而不是字符串)

node.js - 这是服务器代码还是应用程序代码的问题?

javascript - 从 JSON 动态定义 ReactJS 路由