2017-02-25 119 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已经做到了。但是,我仍然发布这个,所以你知道你为什么应该使用状态,而不是参考。