在Component中读取Text Input ref时,未定义React native refs

时间:2016-12-07 15:30:56

标签: javascript reactjs react-native

我的应用程序中有几个组件,每个组件都有一个textInput字段。当每个textInput都提交时,我希望它专注于下一个组件的textInput字段。相反,我在父组件中的函数说:

undefined is not an object (evaluating'_this.refs[nextField].focus')

这是我的代码:

export default class Parent extends React.Component {
....
render() {
    return (
      <ScrollView>
         <View style={{padding:20}}>
             <One
                 ...
                 onSubmitEditing={this.focusNextField("2")} />

              <TWO
                 .../>
    )
  }
focusNextField = (nextField) => {
    alert(nextField)
    this.refs[nextField].focus()
 }
}

export default class One extends React.Component {
    render() {
        return (
             <View style={{paddingBottom:5}}>
                <TextInput
                 ref="1"
                 style={{height:60,paddingLeft:20}}
                 placeholder="Enter your name"
                 onSubmitEditing={this.props.onSubmitEditing} />
             </View>
     )
  }
}


export default class Two extends React.Component {
    render() {
        return (
           <View style={{paddingBottom:5}}>
               <TextInput
               ref="2"
               keyboardType="phone-pad"
               style={{height:60,paddingLeft:20}}
               placeholder="Enter your age" />
          </View>
      )
   }
}

如何使用来自不同组件的refs

1 个答案:

答案 0 :(得分:1)

要访问其他组件的引用,您还需要将该组件作为ref访问。例如this.refs[nextField].refs[childref]。通过这种方式,您可以沿树下行走     要访问DOM元素,您应该使用React.findDOMNode()

export default class Parent extends React.Component {
....
render() {
    return (
      <ScrollView>
         <View style={{padding:20}}>
             <One
                 ...
                 onSubmitEditing={this.focusNextField.bind(this, "two","2")} />

              <TWO ref="two"
                 .../>
    )
  }
focusNextField = (nextField, childref) => {
    alert(nextField)
    React.findDOMNode(this.refs[nextField].refs[childref]).focus();
 }
}

export default class One extends React.Component {
    render() {
        return (
             <View style={{paddingBottom:5}}>
                <TextInput
                 ref="1"
                 style={{height:60,paddingLeft:20}}
                 placeholder="Enter your name"
                 onSubmitEditing={this.props.onSubmitEditing} />
             </View>
     )
  }
}


export default class Two extends React.Component {
    render() {
        return (
           <View style={{paddingBottom:5}}>
               <TextInput
               ref="2"
               keyboardType="phone-pad"
               style={{height:60,paddingLeft:20}}
               placeholder="Enter your age" />
          </View>
      )
   }
}