专注于导入组件的 TextInput
Focus on TextInput from imported Component
我的组件中有一个 TextInput
(FirstComponent
)。我可以通过调用 this.refs
从组件中调用焦点。我还导入并调用了另一个组件 (SecondComponent
),它也需要在单击按钮时关注 TextInput
。
我的第一个组件:
Import SecondComponent from './SecondComponent';
<View>
<TouchableOpacity
onPress={()=>this.refs.MyBox.focus()}
>
<Text>Open</Text>
</TouchableOpacity>
<SecondComponent />
<TextInput
ref='MyBox'
style={{width: '100%', borderColor: 'gray', borderWidth: 1}}
/>
</View>
SecondComponent
也有一个TouchableOpacity
来调用焦点TextInput
:
<View>
<TouchableOpacity
onPress={()=>this.refs.MyBox.focus()}
>
<Text>Open</Text>
</TouchableOpacity>
</View>
SecondComponent 渲染良好,但无法在 TextInput
上调用焦点,因为它不在 SecondComponent 中。我该如何解决?
谢谢。
您可以直接将引用传递给 TextInput
:
<SecondComponent textInput={this.refs.MyBox} />
然后在SecondComponent
中调用this.props.textInput.focus()
,或者你可以传入进行聚焦的函数并在第二个组件中调用它:
focusOnTextInput = () => this.refs.MyBox.focus();
<View>
<TouchableOpacity
onPress={this.focusOnTextInput}>
...
<SecondComponent onPress={this.focusOnTextInput}/>
然后在SecondComponent
:
onPress={this.props.onPress}
组件的引用不能从另一个组件调用。在您的情况下,您需要在父组件中设置方法,该方法需要一个组件需要聚焦,并将其聚焦。然后将此方法作为 props 传递给子组件。
focusMethod(component) {
component.focus()
}
this.props.focusMethod(this.refs.MyBox);
我的组件中有一个 TextInput
(FirstComponent
)。我可以通过调用 this.refs
从组件中调用焦点。我还导入并调用了另一个组件 (SecondComponent
),它也需要在单击按钮时关注 TextInput
。
我的第一个组件:
Import SecondComponent from './SecondComponent';
<View>
<TouchableOpacity
onPress={()=>this.refs.MyBox.focus()}
>
<Text>Open</Text>
</TouchableOpacity>
<SecondComponent />
<TextInput
ref='MyBox'
style={{width: '100%', borderColor: 'gray', borderWidth: 1}}
/>
</View>
SecondComponent
也有一个TouchableOpacity
来调用焦点TextInput
:
<View>
<TouchableOpacity
onPress={()=>this.refs.MyBox.focus()}
>
<Text>Open</Text>
</TouchableOpacity>
</View>
SecondComponent 渲染良好,但无法在 TextInput
上调用焦点,因为它不在 SecondComponent 中。我该如何解决?
谢谢。
您可以直接将引用传递给 TextInput
:
<SecondComponent textInput={this.refs.MyBox} />
然后在SecondComponent
中调用this.props.textInput.focus()
,或者你可以传入进行聚焦的函数并在第二个组件中调用它:
focusOnTextInput = () => this.refs.MyBox.focus();
<View>
<TouchableOpacity
onPress={this.focusOnTextInput}>
...
<SecondComponent onPress={this.focusOnTextInput}/>
然后在SecondComponent
:
onPress={this.props.onPress}
组件的引用不能从另一个组件调用。在您的情况下,您需要在父组件中设置方法,该方法需要一个组件需要聚焦,并将其聚焦。然后将此方法作为 props 传递给子组件。
focusMethod(component) {
component.focus()
}
this.props.focusMethod(this.refs.MyBox);