【问题标题】:unable to access component with ref无法使用 ref 访问组件
【发布时间】:2018-10-09 22:58:57
【问题描述】:

为什么 this.workmin.value 未定义?

captureInput=(text)=>{
    console.log('captureinput',this.refs.workmin.value)
  }

  render() {
    console.log('RENDER',this.state)


    return (
      <View style={styles.container}>
        <Text style={styles.bigFont}>{`${this.state.timer + 'TIMER'}`}</Text>
        <Text style={styles.bigFont}>{`${this.state.min + ':' + this.state.sec}`}</Text>
        <View style={styles.button}>
          <Button title='START' onPress={()=>this.startToggle()} />
          <Button title='RESET' onPress={()=>this.resetToggle()} />
        </View>
             <View style={styles.row}>
                <Text style={[styles.bold,{marginRight:10},{width:112},
                            {textAlign:'right'}]}>
                            Work Timer:</Text>
                <Text style={styles.bold}> min:</Text>
                <TextInput
                   
                   value={Math.floor(this.state.workTime / 60).toString()}
                   ref= {(ref)=>{this.workmin=ref}}
                   style={styles.input}
                   onChangeText={(text) => {this.captureInput(text)}}

                />
      </View>
    )
  }

【问题讨论】:

    标签: react-native ref


    【解决方案1】:

    refs 已弃用,改为:

    <TextInput
      ref={(ref) => {
        this.workmin = ref;
      }}
    />
    

    然后你可以像this.workmin.focus()一样使用它。

    【讨论】:

    • 如何获取输入字段的值?
    • 你想获取onSubmitEditing中的值吗?将来自onChangeText 的更新文本存储在一个状态:onChangeText={text =&gt; setState({ text })},然后从this.state.text 读取。
    • 我正在尝试确定正在使用的输入字段。我以为我可以通过 ref 识别哪个字段
    • 不要使用 ref ,只是调用不同的处理程序?在stackoverflow.com/questions/50090054/… 上查看我的回答
    • 这似乎不是最好的答案。如果您有 10 个输入字段,您真的要复制 10 个处理程序吗?
    猜你喜欢
    • 2021-03-26
    • 1970-01-01
    • 2018-01-03
    • 2021-09-22
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 2022-11-17
    相关资源
    最近更新 更多