reactjs - 渲染传递的组件渲染函数
问题描述
我试图了解如何在另一个函数中调用传递的组件渲染函数。假设我有两个要调用的函数(A 和 B):
export const A = (value: any) => {
return (
<div>{value}</div>
);}
export const B = (value: any) => {
return (
<table>
<thead>
<tr>
<th>Source</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{value.map((item: any) => {
<span>
<td>{Object.keys(item)}</td>
<td>{Object.values(item)}</td>
</span>
})}
</tbody>
</table>
);}
我想将这两个组件传递给另一个组件,并让传递的组件在接收组件中呈现。因此,如果我像这样将它们传递给 CollapsibleSection 组件:
export class MeasureSection extends React.Component<any, any> {
constructor(props: any) {
super(props);
}
public render() {
const { data } = this.props;
return (
<div>
{data && data.map(({ ValueA, ValueB }: any, index: number) =>
<div key={index}>
{ValueA && <CollapsibleSection
isCollapsed={false}
buttonText='A'
collapsibleSection={<A value={ValueA} />}
/>}
{ValueB && <CollapsibleSection
isCollapsed={false}
buttonText='B'
collapsibleSection={<B value={ValueB} />}
/>}
</div>
)}
</div>
);
}
}
CollapsibleSection 组件:
export class CollapsibleSection extends React.Component<any, {isCollapsed: boolean}> {
constructor(props: {}) {
super(props);
this.state = {
isCollapsed: this.props.isExpanded
}
this._toggleCollapse = this._toggleCollapse.bind(this);
}
public render(): JSX.Element {
const { isCollapsed } = this.state;
const { buttonText, collapsibleSection } = this.props;
return (
<div>
<DefaultButton
onClick={this._toggleCollapse} className="CollapsibleSection"
>
{isCollapsed ? <i className="ms-Icon ms-Icon--ChevronUp" aria-hidden="true" /> : <i className="ms-Icon ms-Icon--ChevronDown " aria-hidden="true" />}
{buttonText}
</DefaultButton>
{isCollapsed && collapsibleSection.props.value}
</div>
);
}
private _toggleCollapse() {
this.setState({ isCollapsed: !this.state.isCollapsed })
}
}
在 collapsibleSections 渲染函数中,我想调用传递的组件渲染函数。线
{isCollapsed && collapsibleSection.props.value}
允许我渲染组件 A,但我没有调用渲染,我只是提取值(?)。这种方法不适用于像 B 这样更复杂的组件。那么如何在 CollapsibleSections 渲染函数中调用组件 A 和 B 的渲染函数呢?这种方法是将组件传递给另一个组件的正确方法还是有更聪明的方法?
解决方案
您不必像这样调用collapsibleSection.props.value
,collapsibleSection
因为{isCollapsed && collapsibleSection}
该属性collapsibleSection
将包含您的组件。
推荐阅读
- javascript - 对对象数组中的对象数组中的值进行排序
- scrapy - 提高scrapy crawlera的爬行速度
- javascript - 在 JavaScript 中实现 new BigInteger(130, new SecureRandom()).toString(32)
- python-3.x - 围绕 MongoDB/GridFS BinData 的困惑
- reactjs - 将 opencv4nodejs 导入 React App.js 会引发 TypeError
- html - 如何将默认宽度设置为标题单元格html
- django - 导入错误以某种方式与 app_labels 相关
- python - 对一列列表字符串进行操作
- java - 尽管我已经提到了它的代码,但当我没有提供任何输入时,我的应用程序就会关闭
- jquery - 如何通过 ajax 在局部中使用引导多选控件呈现局部视图