首页 > 解决方案 > 渲染传递的组件渲染函数

问题描述

我试图了解如何在另一个函数中调用传递的组件渲染函数。假设我有两个要调用的函数(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" />}
                    &nbsp; {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 的渲染函数呢?这种方法是将组件传递给另一个组件的正确方法还是有更聪明的方法?

标签: reactjstypescript

解决方案


您不必像这样调用collapsibleSection.props.valuecollapsibleSection因为{isCollapsed && collapsibleSection}该属性collapsibleSection将包含您的组件。


推荐阅读