如何使用react-native-render-html渲染可交互的input输入框?
解决react-native-render-html渲染标签无交互的问题
问题出在你只定义了占位的自定义模型,没有绑定可交互的React Native输入组件。以下是完整实现步骤:
第一步:创建对应的可交互RN组件
把HTML的<input>映射到React Native的TextInput组件,同时处理HTML属性到RN组件props的转换,比如输入类型、默认值、占位符等:import { TextInput, StyleSheet } from 'react-native'; const HtmlInput = ({ domNode, onChange }) => { const { attributes } = domNode; const inputType = attributes.type || 'text'; const defaultValue = attributes.value || ''; return ( <TextInput style={styles.input} keyboardType={inputType === 'number' ? 'numeric' : 'default'} defaultValue={defaultValue} onChangeText={(text) => onChange(text, domNode)} placeholder={attributes.placeholder} autoCapitalize={inputType === 'email' ? 'none' : 'sentences'} /> ); }; const styles = StyleSheet.create({ input: { borderWidth: 1, borderColor: '#ddd', paddingVertical: 6, paddingHorizontal: 8, borderRadius: 4, backgroundColor: '#fff', marginVertical: 4, }, });第二步:定义关联组件的HTMLElementModel
将自定义组件与<input>标签绑定,指定模型的核心参数:import { HTMLElementModel } from 'react-native-render-html'; const inputModel = new HTMLElementModel({ tagName: 'input', component: HtmlInput, isElement: true, attributeNames: ['type', 'value', 'placeholder', 'name'], });第三步:配置RenderHtml使用自定义模型
在RenderHtml组件中传入自定义模型,同时可以添加输入值的回调逻辑:import RenderHtml from 'react-native-render-html'; import { useState } from 'react'; const YourPageComponent = () => { const [formValues, setFormValues] = useState({}); const htmlContent = ` <div style="padding:10px;"> <p>用户名:<input type="text" name="username" placeholder="请输入用户名" /></p> <p>手机号:<input type="number" name="phone" placeholder="请输入手机号" /></p> </div> `; const handleInputChange = (text, domNode) => { const inputName = domNode.attributes.name; if (inputName) { setFormValues(prev => ({ ...prev, [inputName]: text })); } }; return ( <RenderHtml contentWidth={350} source={{ html: htmlContent }} customHTMLElementModels={{ input: inputModel, }} renderersProps={{ input: { onChange: handleInputChange }, }} /> ); };核心说明
之前的黄色盒子是库默认的占位样式,因为你只定义了空模型但没关联可交互组件。现在通过绑定TextInput,就能实现键盘唤起、输入值变更、类型适配等完整交互功能。
内容的提问来源于stack exchange,提问作者Pratham Kumar
相关产品推荐
相关产品推荐

