欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

react寫一個select組件的實現(xiàn)代碼

 更新時間:2019年04月03日 11:07:21   作者:ppsspp  
這篇文章主要介紹了react寫一個select組件的實現(xiàn)代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

之前一直用的antd的Select組件,但在有些端并不適用,而原生的select樣式修改不靈活,遂產生自己寫一個組件的想法。觀察select組件:

<select onChange={(value) => {this.value=value}}
  <option value='1'>man</option>
  <option value='0'>woman</option>
</select>

可以看出數(shù)據(jù)都是在option中,有值value和顯示出來的數(shù)據(jù)一一對應。如果我們寫一個select組件,那么應該有onChange方法,應該要訪問到子元素,而且div是沒有value這個屬性的,所以option應該也是一個組件,有value屬性。下面是我寫的組件的用法:

import {MobileSelect, MobileOption} from '../../components/MobileSelect';

 <MobileSelect
  disabled={isDisabled}
  value={data.clarity || ringResponse.clarity || 'Flawless'}
  style={{ width: '132px' }}
  onChange={(v) => this.changeDataValue('clarity', v)}
 >
  {
   (clarity || []).map((item, i) => {
    return (
     <MobileOption key={i + ''} value={item.code}>{item.title}</MobileOption>
    );
   })
  }
 </MobileSelect>

可以看出其和一般的select組件用法差不多。效果如下:

下面是組件

import {observable} from 'mobx';
import {observer} from 'mobx-react';
import React from 'react';
import {Icon} from 'antd';
import './index.less';

interface IProps {
 disabled?: boolean;
 onChange?: (value) => void;
 value?: string | number;
 style?: React.CSSProperties;
 className?: string;
}
@observer
export class MobileSelect extends React.Component<IProps> {
 @observable showOption = false;   // 是否彈出下拉框
 @observable value: any = '';    // 當前選中的value值
 @observable text: any = '';     // 選中的value值對應的文本
 @observable cell: any;       // 組件的dom節(jié)點
 componentDidMount(): void {
  // 獲取選擇框的ref,當在組件外點擊時的時候收起下拉框
  document.addEventListener('click', (e) => {
   if (this.cell && this.cell !== e.target && !this.cell.contains(e.target)) {
    this.showOption = false;
   }
  }, true);
 }
 componentWillReceiveProps(nextProps: Readonly<IProps>, nextContext: any): void {
  // 根據(jù)傳入的value值,遍歷children,找到對應值的展示文本
  if (nextProps.value !== this.props.value || nextProps.children !== this.props.children) {
   React.Children.map(this.props.children, (child, index) => {
    if (nextProps.value === child.props.value) {
     this.text = child.props.children;
    }
   });
  }
 }
 render(): React.ReactNode {
  const {children, value} = this.props;
  console.log(value);
  return (
   <div
    className={'Mobile-Select ' + this.props.className}
    style={this.props.style}
    ref={(node) => this.cell = node}
   >
    <div
     className={'select-wrap'}
     onClick={() => {
      // 禁用不能彈出下拉框
      if (!this.props.disabled) {
       this.showOption = !this.showOption;
      }
     }}
    >
     <Icon type='down' style={this.showOption ? {transform: 'rotate(180deg)'} : {transform: 'rotate(0deg)'}} className={'select-icon'}/>
     {this.text}
    </div>
    <div className={'option-wrap'} style={this.showOption ? {position: 'absolute'} : {display: 'none'}}>
     {
      React.Children.map(children, (child, index) => {
       // 設置選中option和未選中option的樣式
       let optionClassName = '';
       if (this.props.value === child.props.value) {
        optionClassName = child.props.className ? child.props.className + ' option-item selected' : 'option-item selected';
       } else {
        optionClassName = child.props.className + ' option-item';
       }
       return (
        <div
         onClick={() => {     // 為了在父組件給子組件添加onClick事件,包裹了一層div
          // 有無onChange事件都能改變值
          if (this.props.value && this.props.onChange) {
           this.props.onChange(child.props.value);
          } else {
           this.text = child.props.children;
           this.value = child.props.value;
          }
          console.log(this.value);
          this.showOption = !this.showOption;
         }}
         style={this.props.style}
         className={optionClassName}
        >{child}</div>
       );
      })
     }
    </div>
   </div>
  );
 }
}
interface OptionProps {
 value?: string | number;
 className?: string;
 style?: React.CSSProperties;
}
export class MobileOption extends React.Component<OptionProps> {
 render(): React.ReactNode {
  const {children} = this.props;
  return (
   <div style={this.props.style}>
    {children}
   </div>
  );
 }
}

下面是組件的樣式

.Mobile-Select {
 display: inline-block;
 min-width: 100px;
 margin: 0 6px;
 .select-wrap {
  border: 1px solid #e0c0a2;
  border-radius: 4px;
  padding: 5px 11px;
  display: flex;
  flex-direction: row-reverse;
  justify-content: space-between;
  align-items: center;
  .select-icon {
   transition: .3s;
   float: right;
  }
 }
 .option-wrap {
  box-shadow: 0 0 5px #333;
  z-index: 1000;
  border-radius: 5px;
  .option-item {
   background-color: #fff;
   padding: 2px 11px;
   min-width: 100px;
   &.selected {
    background-color: #fbe6d0;
   }
  }
 }
}

總的來說只實現(xiàn)了select的基本功能。有改進的地方請指點一二。

PS:React Select默認值選中問題

import React from "react";
import { render } from "react-dom";

class App extends React.Component {
 constructor(props) {
  super(props);
  this.state = {
   projects: [],
   value: ""
  };
 }
 componentDidMount() {
  // 模擬ajax調用,成功之后把需要改變的默認值賦值給this.state.value
  setTimeout(() => {
   this.setState({
    projects: [
     { id: 1, name: "花生" },
     { id: 2, name: "蘋果" },
     { id: 3, name: "楊桃" }
    ],
    value: 1
   });
  }, 3000);
 }
 handleClick() {
  this.setState({
   projects: [
    { id: 4, name: "水果" },
    { id: 5, name: "西瓜" },
    { id: 6, name: "哈哈哈" }
   ],
   value: 4
  });
 }
 handleChange = e => {
  this.setState({
   value: e.target.value
  });
 };
 render() {
  let projects = this.state.projects;
  return (
   <div>
    <button onClick={this.handleClick.bind(this)}>異步拉取數(shù)據(jù)</button>
    {/* 這里不用再去判斷project的長度是否大于0,在ajax里面做判斷就行,如果小于零或者不存在它就是默認值 */}
    <select
     defaultValue=""
     value={this.state.value}
     onChange={this.handleChange}
    >
     {projects.length > 0 &&
      projects.map((item, i) => {
       return (
        <option key={i} value={item.id}>
         {item.name}
        </option>
       );
      })}
    </select>
   </div>
  );
 }
}

render(<App />, document.getElementById("root"));

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • 2個奇怪的react寫法

    2個奇怪的react寫法

    大家好,我卡頌。雖然React官網(wǎng)用大量篇幅介紹最佳實踐,但因JSX語法的靈活性,所以總是會出現(xiàn)奇奇怪怪的React寫法。本文介紹2種奇怪(但在某些場景下有意義)的React寫法。也歡迎大家在評論區(qū)討論你遇到過的奇怪寫法
    2023-03-03
  • React.js綁定this的5種方法(小結)

    React.js綁定this的5種方法(小結)

    this在javascript中已經(jīng)相當靈活,這篇文章主要介紹了React.js綁定this的5種方法(小結),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-06-06
  • React中useEffect與生命周期鉤子函數(shù)的對應關系說明

    React中useEffect與生命周期鉤子函數(shù)的對應關系說明

    這篇文章主要介紹了React中useEffect與生命周期鉤子函數(shù)的對應關系說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-09-09
  • React父子組件互相通信的實現(xiàn)示例

    React父子組件互相通信的實現(xiàn)示例

    React中是單向數(shù)據(jù)流,數(shù)據(jù)只能從父組件通過屬性的方式傳給其子組件,本文主要介紹了React父子組件互相通信的實現(xiàn)示例,具有一定的參考價值,感興趣的可以了解一下
    2023-11-11
  • React-three-fiber使用初體驗

    React-three-fiber使用初體驗

    這篇文章主要為大家介紹了React-three-fiber的使用初體驗,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-05-05
  • React路由組件傳參的三種方式(params、search、state)

    React路由組件傳參的三種方式(params、search、state)

    本文主要介紹了React路由組件傳參的三種方式,主要包括了params、search、state,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-07-07
  • React Context與setState詳解使用方法

    React Context與setState詳解使用方法

    Context提供了一個無需為每層組件手動添加props,就能在組件樹間進行數(shù)據(jù)傳遞的方法。在一個典型的 React 應用中,數(shù)據(jù)是通過props屬性自上而下(由父及子)進行傳遞的,但這種做法對于某些類型的屬性而言是極其繁瑣的
    2022-11-11
  • reset.css瀏覽器默認樣式表重置(user?agent?stylesheet)的示例代碼

    reset.css瀏覽器默認樣式表重置(user?agent?stylesheet)的示例代碼

    這篇文章主要介紹了reset.css瀏覽器默認樣式表重置(user?agent?stylesheet),本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-12-12
  • react native與webview通信的示例代碼

    react native與webview通信的示例代碼

    本篇文章主要介紹了react native與webview通信的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-09-09
  • 基于PixiJS實現(xiàn)react圖標旋轉動效

    基于PixiJS實現(xiàn)react圖標旋轉動效

    PixiJS是一個開源的基于web的渲染系統(tǒng),為游戲、數(shù)據(jù)可視化和其他圖形密集型項目提供了極快的性能,這篇文章主要介紹了用PixiJS實現(xiàn)react圖標旋轉動效,需要的朋友可以參考下
    2022-05-05

最新評論