渲染传递的组件渲染功能

时间:2018-09-28 07:04:35

标签: reactjs typescript

我试图了解如何在另一个函数内调用传递的组件渲染函数。假设我要调用两个函数(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和Bs渲染函数?这种方法是将组件传递到另一个组件中的正确方法吗?还是有更聪明的方法?

1 个答案:

答案 0 :(得分:1)

您不必像collapsibleSection.props.value那样collapsibleSection来调用{isCollapsed && collapsibleSection},因为属性collapsibleSection将包含您的组件。