2017-02-25 28 views
3

我有以下場景。React Native在輸入焦點時有條件渲染視圖的一部分

function MyComponent() { 
    return (
    <View> 
     <TextInput ref={ref => (this.input = ref)} style={styles.input} /> 
     {this.input.isFocused() && <Text>Hello World</Text>} 
    </View> 
); 
} 

這實際工作正常,但我得到警告:

MyComponent的訪問是其內部的渲染findNodeHandle。渲染 應該是一個純函數。

如何有條件地渲染文本塊並避免此警告?

回答

3

可以使用組件的狀態:

class MyComponent extends React.Component { 

    state = { isFocused: false } 

    handleInputFocus =() => this.setState({ isFocused: true }) 

    handleInputBlur =() => this.setState({ isFocused: false }) 

    render() { 
     const { isFocused } = this.state 

     return (
     <View> 
      <TextInput 
      onFocus={this.handleInputFocus} 
      onBlur={this.handleInputBlur} 
      /> 
      {isFocused && <Text>Hello World</Text>} 
     </View> 
    ) 
    } 
} 
+0

爲什麼不只是'{this.state.isFocused && Hello World}'? – TheJizel

+0

這是一回事,我總是在返回之前從狀態和道具中提取變量。這只是一個約定。 – Freez

1

不能從渲染()方法引用參考文獻。 Read more about the cautions of working with refs here.

如下圖所示,組件第一次裝入時,refs未定義,當我改變文本(其中改變了重新呈現組件的狀態)時,refs現在可用。

This app updates the state on text change of the Text Input and therefore re-renders the component with the proper refs

的最佳的解決辦法是使用狀態。我打算髮布解決方案,但Freez已經做到了。但是,我仍然發佈這個,所以你知道你爲什麼應該使用狀態,而不是參考。