在输入中反应componentWillMount setState没有显示状态值

时间:2016-08-03 14:07:54

标签: javascript reactjs

我是React的新手,在输入或处理状态设置时遇到了一些defaultValue问题。代码示例,说明了这一点:https://jsfiddle.net/4gxqw5c5/

我希望,1-2示例中的输入将具有默认值,但是他显示占位符值。如果检查输入,您将看到已填充的值,但未显示。在示例3中,我使用值属性和输入显示实际值。 我做错了什么?

代码示例:

   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

1 个答案:

答案 0 :(得分:0)

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

相关问题