当输入聚焦时,React Native 有条件地渲染部分视图
React Native conditionally render part of view while input is focused
我有以下场景。
function MyComponent() {
return (
<View>
<TextInput ref={ref => (this.input = ref)} style={styles.input} />
{this.input.isFocused() && <Text>Hello World</Text>}
</View>
);
}
这实际上工作正常,但我收到警告:
MyComponent is accessing findNodeHandle inside its render. render
should be a pure function.
如何有条件地呈现文本块并避免此警告?
您可以使用组件状态:
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>
)
}
}
您不能从 render() 方法引用引用。 Read more about the cautions of working with refs
here.
如下图所示,第一次挂载组件时,refs 未定义,当我更改文本(更改状态,重新渲染组件)时,refs 现在可用。
最佳解决方案是使用状态。我打算 post 一个解决方案,但 Freez 已经做到了。但是,我仍在 post 进行此操作,以便您知道为什么应该使用 state 而不是 refs。
我有以下场景。
function MyComponent() {
return (
<View>
<TextInput ref={ref => (this.input = ref)} style={styles.input} />
{this.input.isFocused() && <Text>Hello World</Text>}
</View>
);
}
这实际上工作正常,但我收到警告:
MyComponent is accessing findNodeHandle inside its render. render should be a pure function.
如何有条件地呈现文本块并避免此警告?
您可以使用组件状态:
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>
)
}
}
您不能从 render() 方法引用引用。 Read more about the cautions of working with refs
here.
如下图所示,第一次挂载组件时,refs 未定义,当我更改文本(更改状态,重新渲染组件)时,refs 现在可用。
最佳解决方案是使用状态。我打算 post 一个解决方案,但 Freez 已经做到了。但是,我仍在 post 进行此操作,以便您知道为什么应该使用 state 而不是 refs。