2016-08-11 167 views
3

我有一个TextInput,我想在我的函数中引用。refs not working in react-native

next() { 
     let body = this.refs.body.value 
    } 

<View> 
    <Text>Place the body here</Text> 
    <TextInput ref="body" placeholder="Your body goes here..." style={styles.body} placeholderTextColor='green'/> 
</View> 

但我收到此错误:

undefined is not an object (evaluating 'this.refs.body')

ref不工作的反应,本土?

回答

7

我认为他们已经改变了ref的工作方式。现在,而不是一个字符串,ref接受一个函数,当特定的组件被渲染时被调用。
你可以尝试像,

next() { 
let body = this._textInput.value 
} 

<View> 
    <Text>Place the body here</Text> 
    <TextInput ref={component => this._textInput = component} placeholder="Your body goes here..." style={styles.body} placeholderTextColor='green'/> 
</View> 

https://facebook.github.io/react-native/docs/direct-manipulation.html

或者,你也可以附加一个onchange您TextInput和记录输入点击下一步按钮时。

编辑:
引用仍然接受字符串,但它将被弃用。改为使用ref中的函数。

0

该问题可能与您引用尚未安装的元素有关。您是否确定在componentDidMount或更高版本上提及它?

+1

是的,我认为是。组件渲染后,我可以按下一个按钮。这是否意味着我可以在'componentDidMount'后面按下?我很抱歉,我很新。 –