代码之家  ›  专栏  ›  技术社区  ›  Dan With The Plan

对操纵数字格式的格式做出反应,使其符合工作条件

  •  1
  • Dan With The Plan  · 技术社区  · 8 年前

    我在操作React的格式时遇到问题 NumberFormat .

    我需要它变成 format="(###) ###-####" 如果用户输入10个数字,但当用户广告第11个数字时,格式必须被放弃,但数字仍然显示。

    这就是我迄今为止所尝试的:

    import React, { Component } from "react";
    import NumberFormat from "react-number-format";
    import PhoneInputHandler from "./PhoneInputHandler/PhoneInputHandler";
    class App extends Component {
      state = {
        userInput: ""
      };
      phoneNumberFormatHandler = values => {
        console.log(values);
        //  this.state.userInput.length <= 10 ? this.format="(###) ###-####" : this.format=this.state.userInput.values
      };
      render() {
        return (
          <div className="App">
            {/* <input type="number"
                name="phoneNumberInput"
                placeholder='Phone Number Here'
                onChange={this.inputChangedHandler}
                value={this.state.userInput}/>
                format="(###) ###-####"
                <p id='PhoneOutput'><strong>Value: </strong>+1{this.state.numAsString}</p>
                 */}
            <NumberFormat
              format="(###) ###-####"
              mask=""
              name="phoneNumberInput"
              placeholder="Phone Number Here"
              onValueChange={this.inputChangedHandler}
              value={this.state.userInput.value}
            />
            <p>
              <strong>Value: </strong>+1{this.state.userInput.value}
            </p>
          </div>
        );
      }
    }
    
    export default App;
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Tholle    8 年前

    你可以再加一个 # 在格式字符串的末尾,检查 userInput 有一个 length 少于11只给予 NumberFormat format 如果是这样的话,请支持。

    例子

    class App extends Component {
      state = {
        userInput: ""
      };
    
      inputChangedHandler = values => {
        this.setState({ userInput: values.value });
      };
    
      render() {
        const { userInput } = this.state;
    
        return (
          <div className="App">
            <NumberFormat
              format={userInput.toString().length < 11 ? "(###) ###-#####" : undefined}
              name="phoneNumberInput"
              placeholder="Phone Number Here"
              onValueChange={this.inputChangedHandler}
              value={userInput}
            />
            <p>
              <strong>Value: </strong>+1{userInput}
            </p>
          </div>
        );
      }
    }
    
    推荐文章