React - change input defaultValue by passing props

后端 未结 7 1957
星月不相逢
星月不相逢 2020-12-24 13:02

Consider this example:

var Field = React.createClass({
    render: function () {
        // never renders new value...
        return (
            

        
7条回答
  •  有刺的猬
    2020-12-24 13:41

    defaultValue only works for the initial load. After that, it won't get updated. You need to maintain the state for you Field component:

    var Field = React.createClass({
        //transfer props to state on load
        getInitialState: function () {
            return {value: this.props.value};
        },
        //if the parent component updates the prop, force re-render
        componentWillReceiveProps: function(nextProps) {
             this.setState({value: nextProps.value});
        },
        //re-render when input changes
        _handleChange: function (e){
            this.setState({value: e.target.value});
        },
        render: function () {
            // render based on state
            return (
                
    ); } });

提交回复
热议问题