React input defaultValue doesn't update with state

后端 未结 5 1612
孤街浪徒
孤街浪徒 2020-11-28 05:27

I\'m trying to create a simple form with react, but facing difficulty having the data properly bind to the defaultValue of the form.

The behavior I\'m looking for is

5条回答
  •  粉色の甜心
    2020-11-28 06:13

    The most reliable way to set initial values is to use componentDidMount(){} in addition to render(){}:

    ... 
    componentDidMount(){
    
        const {nameFirst, nameSecond, checkedStatus} = this.props;
    
        document.querySelector('.nameFirst').value          = nameFirst;
        document.querySelector('.nameSecond').value         = nameSecond;
        document.querySelector('.checkedStatus').checked    = checkedStatus;        
        return; 
    }
    ...
    

    You may find it easy to destroy an element and replacing it with the new one with

    
    

    like this:

    if(document.querySelector("#myParentElement")){
        ReactDOM.unmountComponentAtNode(document.querySelector("#myParentElement"));
        ReactDOM.render(
            ,
            document.querySelector("#myParentElement")
        );
    };
    

    You can use also this version of unmount method:

    ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(this).parentNode);
    

提交回复
热议问题