如何强制在React组件上重新安装?

JavaScript

Monkey洋

2020-03-12

可以说我有一个具有条件渲染的视图组件:

render(){
    if (this.state.employed) {
        return (
            <div>
                <MyInput ref="job-title" name="job-title" />
            </div>
        );
    } else {
        return (
            <div>
                <MyInput ref="unemployment-reason" name="unemployment-reason" />
                <MyInput ref="unemployment-duration" name="unemployment-duration" />
            </div>
        );
    }
}

MyInput看起来像这样:

class MyInput extends React.Component {

    ...

    render(){
        return (
            <div>
                <input name={this.props.name} 
                    ref="input" 
                    type="text" 
                    value={this.props.value || null}
                    onBlur={this.handleBlur.bind(this)}
                    onChange={this.handleTyping.bind(this)} />
            </div>
        );
    }
}

可以说employed是真的。每当我将其切换为false并渲染另一个视图时,只会unemployment-duration重新初始化。还会unemployment-reason从中预填充值job-title(如果条件更改之前已给出值)。

如果我将第二个渲染例程中的标记更改为如下所示:

render(){
    if (this.state.employed) {
        return (
            <div>
                <MyInput ref="job-title" name="job-title" />
            </div>
        );
    } else {
        return (
            <div>
                <span>Diff me!</span>
                <MyInput ref="unemployment-reason" name="unemployment-reason" />
                <MyInput ref="unemployment-duration" name="unemployment-duration" />
            </div>
        );
    }
}

似乎一切正常。看起来React只是无法区分'职位-头衔'和'失业原因'。

请告诉我我做错了什么...

第1219篇《如何强制在React组件上重新安装?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
HarryStafan 2020.03.12

更改组件的键。

<Component key="1" />
<Component key="2" />

由于密钥已更改,因此将卸载Component并安装新的Component实例。

编辑:记录在您上可能不需要派生状态

当一个键改变时,React将创建一个新的组件实例,而不是更新当前实例。键通常用于动态列表,但在这里也很有用。

西里阿飞 2020.03.12

使用setState在视图中改变employed状态的财产。这是React渲染引擎的示例。

 someFunctionWhichChangeParamEmployed(isEmployed) {
      this.setState({
          employed: isEmployed
      });
 }

 getInitialState() {
      return {
          employed: true
      }
 },

 render(){
    if (this.state.employed) {
        return (
            <div>
                <MyInput ref="job-title" name="job-title" />
            </div>
        );
    } else {
        return (
            <div>
                <span>Diff me!</span>
                <MyInput ref="unemployment-reason" name="unemployment-reason" />
                <MyInput ref="unemployment-duration" name="unemployment-duration" />
            </div>
        );
    }
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android