我正在尝试将数据从 native iOS 应用程序传输到在 UIWebView 中运行的 React(非 native react )网络应用程序。
我从 native View Controller 获取一个字符串,需要将其“注入(inject)”到 <input>
的值中React 组件类中的元素。我给元素一个 id
像这样:
render() {
<div>
...
<input id="iccid" type="text" name="iccid" pattern="\d*" onChange={this.iccidChanged.bind(this)} autoFocus />
...
</div>
}
然后使用来自 iOS(Swift 代码)的 JavaScriptCore 我运行:
self.context = self.webView.valueForKeyPath("documentView.webView.mainFrame.javaScriptContext") as? JSContext
self.context!.evaluateScript("document.getElementById('iccid').value='\(barcodeValue)';")
这似乎工作正常,我可以在 webview 内的 DOM 中看到更新的值,问题是我的 React onChange
函数(验证值并更改组件状态)不会触发,因为 React 不会将此解释为更改(可能是因为 DOM 与虚拟 DOM 处理)。
从 iOS 更新元素值并让 React 组件表现得像用户输入的正确方法/最佳实践是什么?
最佳答案
我假设您想在扫描条形码时触发一个事件。您的 iOS 应用程序可能不需要知道应将事件分派(dispatch)到何处(即哪个输入字段以及如何分派(dispatch))。只需向 Web View 发出条形码已扫描的信号就足够了。
您可以将自定义 DOM 事件分派(dispatch)到 window
并让一些 React 组件监听该事件。
window.dispatchEvent(new CustomEvent('barcodescan', {
detail: {
value: '(barcodeValue)'
}
}))
然后您可以创建一个非渲染组件来监听条形码事件:
const BarcodeListener = React.createClass({
propTypes: {
onBarcodeScan: React.PropTypes.func.isRequired
},
componentDidMount () {
window.addEventListener('barcodescan', this.handleBarcodeScan)
},
componentWillUnmount () {
window.removeEventListener('barcodescan', this.handleBarcodeScan)
},
render () {
return null
},
handleBarcodeScan (e) {
this.props.onBarcodeScan(e)
}
})
然后,在您的表单中,您可以将输入与条形码事件监听器一起呈现:
render () {
return (
<div>
...
<input ... />
<BarcodeListener onBarcodeScan={this.handleBarcodeScan} />
</div>
)
}
然后单独处理条码扫描事件。
关于javascript - 从 iOS UIWebView 更新 React 组件中元素的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34080370/