简体   繁体   中英

Can't set defaultValue of ToggleButtonGroup

When I load my ToggleButtonRadio component with data from componentWillReceiveProps(nextProps) the defaultValue appears to populate with undefined and then doesn't update when data comes through. The component works as expect if data comes from constructor(props) as the defaultValue is set when the component is created. I'm not getting an error so I can't figure out what I'm missing.

This is the react-bootstrap component.

Component: ToggleButtonRadio

const ToggleButtonRadio = (props) => (
  <div>
    <ButtonToolbar key={props.name}>
      <ToggleButtonGroup type="radio" name={props.name} defaultValue={props.selectedOption}>
        {props.options.map(opt =>
          <ToggleButton
            key={opt}
            value={opt}
            onChange={props.controlFunc}>{opt}
          </ToggleButton>
        )}
      </ToggleButtonGroup>
    </ButtonToolbar>
  </div>
);

Page: JobDetailsPage

export default class JobDetailsPage extends React.Component {
  constructor(props) {
    super(props);

    const jobsCollection = props.jobsCollection;
    const contractType = jobsCollection && jobsCollection.contractType;

    this.state = {
      contractType: contractType
    };
  }

  componentWillReceiveProps(nextProps) {
    const jobsCollection = nextProps.jobsCollection;
    const contractType = jobsCollection && jobsCollection.contractType;

    this.setState({
      contractType: contractType
    });
  }

  render() {
    return (
      <div>
        <ToggleButtonRadio
          options={['Permanent', 'Part time', 'Contract', 'Temp']}
          name={'contractType'}
          label={'Contract type'}
          controlFunc={this.handleInputChange}
          selectedOption={this.state.contractType}
        />
      </div>
    );
  }
}

The solution that seems to work is to add a key.

<ToggleButtonRadio
 key={this.state.contractType ? 'loaded' : 'notLoaded'}
 options={['Permanent', 'Part time', 'Contract', 'Temp']}
 name={'contractType'}
 label={'Contract type'}
 controlFunc={this.handleInputChange}
 selectedOption={this.state.contractType}
/>

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