如何在tcomb-form-native的输入框中嵌入自定义组件?
To embed a custom component inside your comment input field using tcomb-form-native, you’ll need to override the default input renderer for your comment field. Here’s a step-by-step solution tailored to your existing setup:
1. Create a Custom Input Component
First, build a reusable component that combines the text input with your embedded UI element. This component will receive all necessary props from tcomb-form-native to maintain form functionality:
import React from 'react'; import { View, TextInput, TouchableOpacity, Text } from 'react-native'; // Replace with your actual embedded component (e.g., icon, button, etc.) const CustomCommentInput = (props) => { // Extract props needed for the text input and your custom component const { onChange, value, placeholder, returnKeyType, onSubmitEditing, stylesheet } = props; return ( <View style={[stylesheet.textbox.container, { flexDirection: 'row', alignItems: 'center' }]}> {/* The core text input */} <TextInput style={[stylesheet.textbox.normal, { flex: 1 }]} placeholder={placeholder} value={value} onChangeText={onChange} returnKeyType={returnKeyType} onSubmitEditing={onSubmitEditing} /> {/* Your embedded component here (example: a send button) */} <TouchableOpacity onPress={onSubmitEditing} style={{ marginLeft: 8, paddingHorizontal: 12 }}> <Text style={{ color: '#007AFF', fontWeight: '600' }}>Post</Text> </TouchableOpacity> </View> ); };
2. Update Your Form Options
Modify your commentFormOptions to use the custom renderer for the comment field. Add the render property pointing to your new component:
commentFormOptions = { fields: { comment: { label: 'What do you think?', placeholder: 'Type your reply', stylesheet: InputStylesheet, returnKeyType: 'done', onSubmitEditing: () => { this.postComment(); }, // Use the custom input renderer render: (formFieldProps) => <CustomCommentInput {...formFieldProps} /> }, }, };
3. Ensure Your Form Setup is Complete
Double-check your Form component includes the necessary state management and type definition. Here’s how it should fit into your existing view structure:
<View style={styles.container}> <KeyboardAvoidingView style={styles.commentForm}> <Form ref={ref => this.form = ref} // Define your form structure (comment is a required string) type={t.struct({ comment: t.String })} options={this.commentFormOptions} // Manage form state value={this.state.formData} onChange={(newValue) => this.setState({ formData: newValue })} /> </KeyboardAvoidingView> </View>
Key Notes:
- The
renderproperty in the field options lets you completely replace the default input with your custom UI. - All props required for the text input (like
onChange,value, and styling) are passed automatically to your custom component viaformFieldProps. - You can replace the example send button with any component you need (icons, dropdowns, etc.)—just adjust the JSX inside
CustomCommentInput.
内容的提问来源于stack exchange,提问作者Joseph Chambers

