gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:55:30 24 4
gpt4 key购买 nike

我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com