【问题标题】:ReactJS render element by refReactJS 通过 ref 渲染元素
【发布时间】:2019-01-02 04:55:48
【问题描述】:

我正在尝试渲染一个有两个孩子的父组件。子项的渲染将切换,因此一次只会渲染第一个子项,另一次将是最后一个子项,最后将切换回第一个子项(然后应该包含之前显示的所有值)。 我以为这很简单,但结果并非如此。

现在问题来了:每当调用 switchContainer 方法时,它都会切换容器并渲染另一个容器。然而,所有成员变量、道具和状态都丢失了,它基本上从头开始重新实例化子组件。

有没有办法“按原样”保存子组件,一旦重新渲染,它将再次保存所有成员变量、道具和状态?

我知道你可以像这样向元素发送道具和状态:

<Child props={<data>} states={<data>}>

但这并不能解决缺少成员变量的问题,而且我认为这不是一个顺利的解决方案。

到目前为止我的尝试是(这只是一个模型):

class Parent extends React.Component<any,any> {
  private firstContainer:any;
  private secondContainer:any;
  private currentContainer:any;
  constructor(props:any) {
        super(props);
        this.firstContainer = <Child>;
        this.secondContainer = <Child>;
    }
    public render() {
        return (
            <div>
                {this.currentContainer}
            </div>
        );
    }
    public switchContainer() {
        if(this.currentContainer === this.firstContainer) {
            this.currentContainer = this.secondContainer;
        }
        else {
            this.currentContainer = this.firstContainer;
        }
        this.forceUpdate();
    }
}


class Child extends React.Component<any,any> {
    private anyValue:string;
    constructor(props) {
        this.change = this.change.bind(this);
    }
    public render() {
        return (
            <input onChange={this.change} value={this.anyValue}/>
        );
    }
    private change(e:any) {
        this.anyValue = e.target.value;
    }
}

【问题讨论】:

    标签: reactjs typescript tsx react-tsx


    【解决方案1】:

    您可以尝试在渲染中维护状态并更新子级,而不是将子级保存为 firstContainer 和 secondContainer

    class Parent extends React.Component<any, any> {
        constructor(props) {
            super(props);
            this.state = {
                firstChild: true
            };
        }
    
        public render() {
            const { firstChild } = this.state;
            <div>
                <Child1 show={firstChild}/>
                <Child2 show={!firstChild} />
            </div>
        }
    
        public switchContainer() {
            this.setState(({ firstChild }) => ({ firstChild: !firstChild }));
        };
    }
    

    在子组件中,将 show 处理为 showContent,否则呈现 null。如果要保留状态,则不应卸载组件。

    【讨论】:

    • 感谢您的快速回答,不幸的是,这是不可能的,因为孩子可以“即时”添加并且从一开始就不知道。因此,一旦添加了新的孩子,父组件总是必须重新渲染孩子。在您的示例中,每当“firstChild”发生变化时,孩子都会重新呈现,因此成员变量“anyValue”再次丢失。
    • 您可以将任何值作为状态存储在父组件中。
    猜你喜欢
    • 2018-03-10
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多