【问题标题】:React manipulating NumberFormat format to work conditional反应操纵 NumberFormat 格式以有条件地工作
【发布时间】:2018-12-23 05:10:45
【问题描述】:

我在处理 React 的 NumberFormat 的格式时遇到问题。

如果用户输入 10 个数字,我需要它变成 format="(###) ###-####",但是当用户广告第 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;

【问题讨论】:

    标签: javascript reactjs number-formatting data-manipulation


    【解决方案1】:

    您可以在格式字符串的末尾添加另一个#,并检查您的userInput 是否有一个小于11 的length,如果是这样的话,只给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>
        );
      }
    }
    

    【讨论】:

    • 您好 Tholle,感谢您的编辑和回复。不幸的是,这不能按预期工作。

      不再输出该值,并且格式仍然阻止我从第 11 个输入开始写入。

    • @DanWithThePlan 你是对的,对此感到抱歉。我更新了答案并添加了一个工作示例。
    • Tholle 非常感谢您!我整个周末都在为此苦苦挣扎。正如你可以想象的那样,这是初级工作考试的一部分。我还有一段路要走,我想我还不会申请。
    猜你喜欢
    • 2019-07-02
    • 2021-03-15
    • 1970-01-01
    • 2020-12-10
    • 2013-06-28
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多