jjzjj

javascript - 自定义日期组件的重构代码

coder 2024-07-22 原文

我创建了一个日期组件(底部的工作 GIF)。

代码的工作没有问题,但我写的代码看起来很乱,其他人很难理解。

注意:请看下面的 GIF。另外,忽略样式

这就是我正在做的。对于屏幕中的日期组件,我正在创建这样的引用和状态

class OnBoarding extends PureComponent {
    constructor(props) {
        super(props)
        this.d1 = React.createRef()
        this.d2 = React.createRef()
        this.d3 = React.createRef()
        this.d4 = React.createRef()
        this.d5 = React.createRef()
        this.d6 = React.createRef()
        this.d7 = React.createRef()
        this.d8 = React.createRef()
    }
    state = {
        name: '',
        emailAddress: '',
        dob: '',
        male: null,
        female: null,
        keyboard: false,
        d1: null,
        d2: null,
        d3: null,
        d4: null,
        d5: null,
        d6: null,
        d7: null,
        d8: null
    }

dobHandler(number, flag) {
        const completeFlag = `d${flag}`
        this.setState({[completeFlag]: number})
        flag = flag + 1
        if (flag < 9 && number) {
            const nextFlag = `d${flag}`
            const textInputToFocus = this[nextFlag]
            textInputToFocus.current.focus()
        }
    }

然后像这样渲染它们

       <View style={styles.dob}>
                        <TextInput
                            ref={this.d1}
                            numberOfLines={1}
                            maxLength={1}
                            style={styles.textInputDob}
                            keyboardType="numeric"
                            placeholder="D"
                            onChangeText={number => this.dobHandler(number, 1)}
                        />
                        <TextInput
                            ref={this.d2}
                            numberOfLines={1}
                            maxLength={1}
                            style={styles.textInputDob}
                            keyboardType="numeric"
                            placeholder="D"
                            onChangeText={number => this.dobHandler(number, 2)}
                        />
                        <Text>/</Text>
                        <TextInput
                            ref={this.d3}
                            numberOfLines={1}
                            maxLength={1}
                            style={styles.textInputDob}
                            keyboardType="numeric"
                            placeholder="M"
                            onChangeText={number => this.dobHandler(number, 3)}
                        />
                        <TextInput
                            ref={this.d4}
                            numberOfLines={1}
                            maxLength={1}
                            style={styles.textInputDob}
                            keyboardType="numeric"
                            placeholder="M"
                            onChangeText={number => this.dobHandler(number, 4)}
                        />
                        <Text>/</Text>
                        <TextInput
                            ref={this.d5}
                            numberOfLines={1}
                            maxLength={1}
                            style={styles.textInputDob}
                            keyboardType="numeric"
                            placeholder="Y"
                            onChangeText={number => this.dobHandler(number, 5)}
                        />
                        <TextInput
                            ref={this.d6}
                            numberOfLines={1}
                            maxLength={1}
                            style={styles.textInputDob}
                            keyboardType="numeric"
                            placeholder="Y"
                            onChangeText={number => this.dobHandler(number, 6)}
                        />
                        <TextInput
                            ref={this.d7}
                            numberOfLines={1}
                            maxLength={1}
                            style={styles.textInputDob}
                            keyboardType="numeric"
                            placeholder="Y"
                            onChangeText={number => this.dobHandler(number, 7)}
                        />
                        <TextInput
                            ref={this.d8}
                            numberOfLines={1}
                            maxLength={1}
                            style={styles.textInputDob}
                            keyboardType="numeric"
                            placeholder="Y"
                            onChangeText={number => this.dobHandler(number, 8)}
                        />
                    </View>

我做了这么多 ref 的原因是因为当有人在当前 textInput 中输入内容时,我希望焦点移动到下一个,这发生在 dobHandler 函数中。

有人可以帮助我提高质量/优化,如果这是错误的做法,请提示我如何实现此替代方案

最佳答案

在很多方法中,你可以这样写,

const placeholders = [ 'D', 'D', 'M', 'M', 'Y', 'Y', 'Y', 'Y'];

class OnBoarding extends PureComponent {
  constructor(props) {
    super(props)
    this.refs = Array(8).fill(0).map(_ => React.createRef())
  }

  state = {
    name: '',
    emailAddress: '',
    male: null,
    female: null,
    keyboard: false,
    dob: Array(8).fill(null)
  }

  dobHandler(number, index) {
    const { dob } = this.state
    dob[index] = number;
    this.setState({ dob:  [ ...dob ]})
    const ref = this.refs[index + 1]
    if (number && ref && ref.current)
      ref.current.focus()
  }

  render() {
    <View style={styles.dob}>
      {this.refs.map((ref, i) => (
        <>
          <TextInput
            ref={ref}
            numberOfLines={1}
            maxLength={1}
            style={styles.textInputDob}
            keyboardType="numeric"
            placeholder={placeholders[i]}
            onChangeText={number => this.dobHandler(number, i)}
          />
         {(i == 1 || i == 3) && <Text>/</Text>}
       </>        
      ))}
    </View>
  }
}

因为你有一个重复集,你可以使用数组,同时根据索引有条件地在需要的地方插入斜杠。

关于javascript - 自定义日期组件的重构代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56704964/

有关javascript - 自定义日期组件的重构代码的更多相关文章

  1. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  2. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  3. ruby-on-rails - Rails 源代码 : initialize hash in a weird way? - 2

    在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has

  4. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  5. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  6. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  7. ruby-on-rails - date_field_tag,如何设置默认日期? [ rails 上的 ruby ] - 2

    我想设置一个默认日期,例如实际日期,我该如何设置?还有如何在组合框中设置默认值顺便问一下,date_field_tag和date_field之间有什么区别? 最佳答案 试试这个:将默认日期作为第二个参数传递。youcorrectlysetthedefaultvalueofcomboboxasshowninyourquestion. 关于ruby-on-rails-date_field_tag,如何设置默认日期?[rails上的ruby],我们在StackOverflow上找到一个类似的问

  8. ruby-on-rails - Ruby 检查日期时间是否为 iso8601 并保存 - 2

    我需要检查DateTime是否采用有效的ISO8601格式。喜欢:#iso8601?我检查了ruby​​是否有特定方法,但没有找到。目前我正在使用date.iso8601==date来检查这个。有什么好的方法吗?编辑解释我的环境,并改变问题的范围。因此,我的项目将使用jsapiFullCalendar,这就是我需要iso8601字符串格式的原因。我想知道更好或正确的方法是什么,以正确的格式将日期保存在数据库中,或者让ActiveRecord完成它们的工作并在我需要时间信息时对其进行操作。 最佳答案 我不太明白你的问题。我假设您想检查

  9. ruby - 检查日期是否在过去 7 天内 - 2

    我的日期格式如下:"%d-%m-%Y"(例如,今天的日期为07-09-2015),我想看看是不是在过去的七天内。谁能推荐一种方法? 最佳答案 你可以这样做:require"date"Date.today-7 关于ruby-检查日期是否在过去7天内,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/32438063/

  10. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

随机推荐