当输入聚焦时,React Native 有条件地渲染视图的一部分

Ste*_*idi 4 javascript purely-functional reactjs react-native

我有以下场景。

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

这实际上工作正常,但我收到警告:

MyComponent 正在其渲染中访问 findNodeHandle。render 应该是一个纯函数。

如何有条件地呈现文本块并避免此警告?

Fre*_*eez 5

You can use component state :

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>
      )
   }
}
Run Code Online (Sandbox Code Playgroud)