简体   繁体   中英

React componentWillMount setState in input no showing state value

I am new with React and met with some issue with defaultValue on input or in the approach to the setting of state. Example of code, which illustrate this: https://jsfiddle.net/4gxqw5c5/

I expect, what input in 1-2 example will have default value, but he show placeholder value. If you inspect input, you will see what value has filled, but not showed. In example number 3 i use value attribute and input show real value. What i am doing wrong?

Code example:

   const counter = (state = 0, action) => {
        switch(action.type) {
        case 'ACTION':
          return state + 1;
        default:
            return state;
      }
    }

    class Counter extends React.Component {
        constructor(props) {
        super(props)
        this.state = {}
      }

      componentWillMount() {
        this.props.some()
        this.props.some()
        this.props.some()
        this.props.some()
        this.props.some()
        this.props.some()
        this.setState({
            textValue: this.props.value
        })
      }

      componentWillReceiveProps(nextProps) {
        console.log('props', nextProps)
        this.setState({
            textValue: this.props.value
        })
      }

        render() {
        console.log('render with: ',this.state.textValue)
        return (
          <div>
            <b>1.</b> Bootstrap defaultValue: <br/>
            <ReactBootstrap.FormControl
                  name="text"
                  placeholder="Enter Text"
                  maxLength="250"
                  defaultValue={this.state.textValue}
                  required
             /> <hr /> 
             <b>2.</b> Input defaultValue: <br/>
             <input type="text" defaultValue={this.state.textValue} /> <hr />
             <b>3.</b> Input value: <br/>
             <input type="text" value={this.state.textValue} />
          </div> 
        );
        }
    }

    const {createStore} = Redux;
    const store = createStore(counter); // bind reducer

    const render = () => {  
        ReactDOM.render(
        <Counter 
        value={store.getState()} 
        some={() => {
            setTimeout(() => store.dispatch({type: 'ACTION'}), 100)
        }} />,
        document.getElementById('root')
      );
    };

    store.subscribe(render);
    render(); // inital render

对不起愚蠢的问题,在官方文档中找到了答案:) https://facebook.github.io/react/docs/forms.html#control-components

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM