问题描述
我正在尝试找出正确的反应"方式将作为元素的可选道具传递给容器组件,该组件的处理方式与该组件的子组件不同.
举个简单的例子,我有一个 Panel 组件,它渲染它的子组件,它还有一个可选的title"道具(为了这个例子,它是一个元素而不是一个字符串),它被特别渲染(放在一个特殊的地方,在保持抽象的同时有特殊的行为.
一种选择是让一个组件从子项中拉出并专门渲染:
<面板><标题>一些东西</Title>其他一些东西</div></面板>但是,把孩子们拉出来分开处理似乎很奇怪.
这通常在反应中是如何处理的,我什至认为这是正确的方式
解决方案 你不需要做任何特别的事情.只需将标题组件作为道具传递,然后在您希望呈现的任何地方使用 {this.props.title}
:
类面板扩展 React.Component {使成为() {返回 {this.props.title}<div>一些其他的东西......</div></div>;}}类 App 扩展 React.Component {使成为() {var title = <Title>我的标题</Title>;return <面板标题={title}/>;}}如果您没有为 title
属性传递任何值(或者如果该值为 false
、null
或 undefined
) 那么那里什么都不会渲染.
这是 React 中相当常见的模式.
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.
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
解决方案 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}/>;
}
}
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.
This is a fairly common pattern in React.
这篇关于reactjs中如何将可选元素作为prop传递给组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!