React React条件渲染

时间:2018-11-26 13:46:50

标签: reactjs typescript

为什么我通过单击引导按钮更改状态userType时无法重新渲染页面?

import * as React from 'react';
import {ButtonToolbar, ToggleButtonGroup, ToggleButton} from 'react-bootstrap';

import CreatePrivateUser from './Private/'
import CreateProfessionelUser from './Professionel/'

import './style.scss';

interface states {
  userType: string
}

export default class CreateUser extends React.PureComponent <any, states> {

  constructor(props) {
        super(props);

    this.handleChange = this.handleChange.bind(this);    

        this.state = {
      userType: ''
        };
    }


  handleChange(event) {
    let selectedUser = event.target.value;

        this.state = {
      userType: selectedUser
    };
    console.log(this.state.userType);
  }



  render() {
    const userType = this.state.userType;
    let form;

    if (userType === "private") {
      form = <CreatePrivateUser />;
    } else if (userType === "professione") {
      form = <CreateProfessionelUser />;
    }

    return (

    <div>
      create user<br/>
      <ButtonToolbar
        value={this.state.userType}
        onChange={this.handleChange}
      >
        <ToggleButtonGroup type="radio" name="options">
          <ToggleButton value="private">private</ToggleButton>
          <ToggleButton value="professione">professione</ToggleButton>
        </ToggleButtonGroup>
      </ButtonToolbar>

      {form}
    </div>

        );

  }

}

1 个答案:

答案 0 :(得分:0)

不要直接使用setState

设置状态

this.setState({userType: selectedUser})