React——条件渲染不清除输入值

React -- conditional render not clear input value

我的密码是

class Com extends React.Component {
    constructor(props) {
        super(props);
        this.state = {is_clicked: false};
    }

    render() {
        let sub_com1 = () => {
            return (
                <div>Input1:<input/></div>
            );
        };
        let sub_com2 = () => {
            return (
                <div>Input2:<input/></div>
            );
        };
        return (
        <div>
            <div>
                {this.state.is_clicked ? sub_com1() : sub_com2()}
            </div>
            <button onClick={()=>{
                               let is_clicked=this.state.is_clicked;
                               this.setState({is_clicked: !is_clicked});
                            }}>
                Click me
            </button>
        </div>
        );
    }
}

和实时显示:codepen

在这段代码中,我在 Com 的渲染方法中使用了条件渲染。

我期待的

每次我点击按钮时,输入区域应该被清除,因为它被渲染到另一个组件

我遇见的

每次点击按钮,"input1"或"input2"标签都变了,但输入区没有被清除

要解决此问题,您必须向输入元素添加 key 属性,将代码更改为如下所示即可:

class Com extends React.Component {
    constructor(props) {
        super(props);
        this.state = {is_clicked: false};
    }

    render() {
        let sub_com1 = () => {
            return (
                <div>Input1:<input key={1} id='A' /></div>
            );
        };
        let sub_com2 = () => {
            return (
                <div>Input2:<input key={2} id='b' /></div>
            );
        };
        return (
        <div>
            <div>
                {this.state.is_clicked ? sub_com1() : sub_com2()}
            </div>
            <button onClick={()=>{
                               let is_clicked=this.state.is_clicked;
                               this.setState({is_clicked: !is_clicked});
                            }}>
                Click me
            </button>
        </div>
        );
    }
}

ReactDOM.render(
  <Com/>,
  mountNode,
);

以下文章更深入地讨论了它以及为什么元素具有键属性很重要:

全文:keys-in-children-components-are-important

Key is not really about performance, it’s more about identity (which in turn leads to better performance). Randomly assigned and changing values do not form an identity Paul O’Shannessy