使用 Material UI 中的 Dropdown 组件在 React JS 中设置和更新状态

IT技术 javascript reactjs material-ui
2021-05-10 04:24:58

我有这段代码调用 Web 服务并将来自该 WS 的名称显示到 Material UI 的 Dropdown 组件中,

我想要做的是使用来自 WS 的第一个元素设置下拉列表的默认值,并且还能够选择下拉列表中的任何选项,我阅读了一些关于“状态”的内容,但没有得到它真的很好在代码级别。

我是 React 的新手并且自己学习,但一些帮助会很好。

    import React, { Component } from 'react';
    import DropDownMenu from 'material-ui/DropDownMenu';
    import MenuItem from 'material-ui/MenuItem';

    export default class WebserviceTest extends Component {

      constructor(props) {
        super(props);
        this.state = {
        data: [],
       };
       this.renderOptions = this.renderOptions.bind(this);
     }

     componentDidMount() {
     const url = 'https://randomuser.me/api/?results=4';

     fetch(url)
       .then(Response => Response.json())
       .then(findResponse => {
         console.log(findResponse);
         this.setState({
           data: findResponse.results
         });
       });
    }
    //will set wahtever item the user selects in the dropdown
    handleChange(event, index, value) {this.setState({ value });}
    //we are creating the options to be displayed
    renderOptions() {
     return this.state.data.map((dt, i) => {
       return (
         <div key={i}>
           <MenuItem
             label="Select a description"
             value={dt.name.first}
             primaryText={dt.name.first} />
         </div>
       );
     });
    }

    render() {
     return (
       <div>
         <DropDownMenu value={this.state.name} onChange={this.handleChange}>
           {this.renderOptions()}
         </DropDownMenu>
       </div>
     );
   }
  }

提前致谢。

问候。

2个回答

您需要设置所选下拉选项的状态。并将数据的第一个值设置为选定值。

componentDidMount() {
 const url = 'https://randomuser.me/api/?results=4';

 fetch(url)
   .then(Response => Response.json())
   .then(findResponse => {
     console.log(findResponse);
     this.setState({
       data: findResponse.results,
       selected: findResponse.results[0].name.first // need to be sure it's exist
     });
   });
}
handleChange(event, index, value) {this.setState({ selected: value });}
.
.
.
render() {
 return (
   <div>
     <DropDownMenu value={this.state.selected} onChange={this.handleChange}>
       {this.renderOptions()}
     </DropDownMenu>
   </div>
 );

}

更新代码

import React, { Component } from 'react';
import DropDownMenu from 'material-ui/DropDownMenu';
import MenuItem from 'material-ui/MenuItem';

export default class WebserviceTest extends Component {
  constructor() {
    super();
    this.state = {
      data: [],
      selected: '',
    };
    this.renderOptions = this.renderOptions.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }

  componentDidMount() {
    const url = 'https://randomuser.me/api/?results=4';

    fetch(url)
      .then(Response => Response.json())
      .then(findResponse => {
        console.log(findResponse);
        console.log(findResponse.results[0].name.first);
        this.setState({
          data: findResponse.results,
          selected: findResponse.results[0].name.first // need to be sure it's exist
        });
      });
  }
  handleChange(value) {this.setState({ selected: value });}

  //we are creating the options to be displayed
  renderOptions() {
    return this.state.data.map((dt, i) => {
      return (
        <div key={i}>
          <MenuItem
            value={dt.name.first}
            primaryText={dt.name.first} />
        </div>
      );
    });
  }

  render() {
    return (
      <div>
        <DropDownMenu value={this.state.selected} onChange={this.handleChange}>
          {this.renderOptions()}
        </DropDownMenu>
      </div>
    );
  }
}

this.setStatethis.state以特殊方式控制变量每当您使用this.setState它时,它都会render再次运行以检查相应的更改。您想要响应的动态内容应该放在其中,this.state并且应该显示在您的render函数中。

有很多方法可以解决您的问题,但最重要的原则是放置您当前想要呈现的内容(或 ID/索引号),this.statethis.setState根据需要使用它进行更改。

value={this.state.name}应该是您从 返回的数据结构中的单个值fetch,假设这是屏幕上显示的内容。

另外,您忘记了bind this.handleChange在构造函数中。

props在你的构造函数中声明完全没问题。只有当您想this.props在构造函数中使用某些内容时才这样做你是不是,所以它是绝对安全的离开,因为constructor()super()