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