如何在React.js中将可选元素作为道具传递给组件 [英] How to pass optional elements to a component as a prop in reactjs
问题描述
我正在尝试找出正确的反应"方式,以将作为元素的可选道具传递给容器组件,该组件的处理方式不同于该组件的子组件.
I am trying to figure out the proper "react" way to pass in an optional prop that is an Element to a container component, that is handled differently from the children of that component.
对于一个简单的示例,我有一个Panel组件,该组件呈现其子级,还具有一个可选的"title"属性(为示例起见,它是元素而不是字符串),该属性专门进行了渲染(放置在一个特殊的位置,并在保持抽象的同时具有特殊的行为.
For a simple example, I have a Panel component, which renders its children, that also has an optional "title" prop (which is an element rather than a string, for the sake of the example) that gets specially rendered (put in a special spot, with special behaviors in while maintaining the abstraction.
一个选择是拥有一个从子级中拉出并专门渲染的组件:
One option is to have a component which is pulled out of the children and rendered specially:
<Panel>
<Title> some stuff</Title>
<div> some other stuff</div>
</Panel>
但是,像这样将孩子们拉出来并分开处理似乎很奇怪.
But it seems wierd to have the children pulled out and handled separately like that.
这通常是如何应对的,我什至在想这是正确的方式
How is this normally handled in react, and am I even thinking about this the right way
推荐答案
您无需执行任何特殊操作.只需将标题组件作为道具传递,然后在要渲染的任何地方使用 {this.props.title}
:
You don't need to do anything special. Just pass the title component as a prop, and then use {this.props.title}
wherever you want it to be rendered:
class Panel extends React.Component {
render() {
return <div>
{this.props.title}
<div>Some other stuff...</div>
</div>;
}
}
class App extends React.Component {
render() {
var title = <Title>My Title</Title>;
return <Panel title={title}/>;
}
}
如果您未传递 title
道具的任何值(或者该值是 false
, null
或未定义
),那么在那里什么也不会呈现.
If you don't pass any value for the title
prop (or if the value is false
, null
, or undefined
) then nothing will be rendered there.
这是React中相当普遍的模式.
This is a fairly common pattern in React.
这篇关于如何在React.js中将可选元素作为道具传递给组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!