选择默认值被状态覆盖

时间:2019-01-03 13:56:25

标签: reactjs state

我目前遇到问题,我的选择下拉列表默认值被国家/地区覆盖。可能是我想念的简单事情,但是谁能告诉我我做错了什么?

单击按钮后,我想提交表单,但是直到我更改它,才会选择州的第一个值?

请让我知道我是否不清楚或需要其他信息。

谢谢!

//Wrapping container containing the state
class ActionsSegment extends Component {    
    constructor(props) {
        super(props);
        this.state = { value: '' };
    
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
      }
    
      handleChange = (event) => {
        this.setState({value: event.target.value});
        console.log(event.target.value);
      }

    
      handleSubmit(event) {
        console.log((`State passed is: ${this.state.value}`));
        event.preventDefault();
      }
      
      render() {
          const { select, selectLabelTitle } = this.props;
          return (
            <form className="actions-segment" onSubmit={this.handleSubmit}>        
                <FormSelect 
                    select={select}
                    selectLabelTitle={selectLabelTitle}
                    handleChange={this.handleChange}
                    value={this.state.value}
                />
            </form>
        )
    }
}

export default ActionsSegment;


//Component containing the select dropdown
<select className="form-select form__flavour-dropdown" onChange={handleChange}>
      {
        select.map((type, index) => (
          <option value={type.title} key={index}>{type.title}</option>
        ))
      }
    </select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

1 个答案:

答案 0 :(得分:0)

您可以使用所需的任何props值来初始化选择值:

this.state = { value: this.props.whatEverPropsYouLike }

或者您的情况可能是这样的:

this.state = { value: this.props.select[0].title }