2016-08-11 166 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'後面按下?我很抱歉,我很新。 –