【发布时间】:2020-04-17 03:38:27
【问题描述】:
我在 React Native Web 应用程序中有一些参考资料 - 这些参考资料适用于 React Native,但不适用于 RNW。
例如,我有这样的代码:
this.highlight.current._children[i].setNativeProps({ style: { backgroundColor: "black" } });
this.highlight.current._children[i]._children[0]._children[0].setNativeProps({ style: { color: "white" } })
this.highlight.current._children[i]._children[1]._children[0].setNativeProps({ style: { color: "white" } })
基于此:
this.highlight = React.createRef();
作为 props 传入子组件并按原样使用:
<View ref={this.props.highlight}>
它有几个孩子(他们也有嵌套的孩子)。
然而,在网络上,根本没有._children。
我如何访问儿童?
Platform.OS === 'web':
let dom = ReactDOM.findDOMNode(this.highlight.current);
... DOM manipulations
但是如果不是绝对必要的话,这会让人感觉很混乱和代码重复。我宁愿通过 React Native API 直接将我的修改应用于引用。
编辑:更多代码 - 这是我的结构和一些与问题相关的函数。我剪掉了不相关的部分以尝试使我发布的代码更小
class DetailBody extends Component {
constructor() {
super();
}
render() {
return (
<ScrollView >
<Text>{this.props.article.intro}</Text>
<View ref={this.props.highlight}>
{this.props.article.json.results.map((content, index) => (
<View key={index} style={{}}>
{content.pinyin ? (
<Fragment>
<View>
<Text>
{content.pinyin}
</Text>
</View>
<View>
<Text>
{content.simplified}
</Text>
</View>
</Fragment>
) : (
<Fragment>
<View>
<Text>
</Text>
</View>
<View>
<Text>
{content.characters}
</Text>
</View>
</Fragment>
)
}
</View>
))}
</View>
</ScrollView>
)
}
}
class Detail extends Component {
constructor() {
super();
this.state = {
currentVal: 0,
};
this.traverseCharacters = this.traverseCharacters.bind(this)
this.highlight = React.createRef();
}
async traverseCharacters(i) {
this.highlight.current._children[i].setNativeProps({ style: { backgroundColor: "black" } });
this.highlight.current._children[i]._children[0]._children[0].setNativeProps({ style: { color: "white" } })
this.highlight.current._children[i]._children[1]._children[0].setNativeProps({ style: { color: "white" } })
if (i > 0) {
this.clearCharacters(i)
}
}
render() {
return (
<DetailBody {...this.props} article={this.state.article} highlight={this.highlight} />
);
}
}
【问题讨论】:
-
你说的在网络上是什么意思?你能提供你的完整代码吗?
-
我的意思是,代码在适用于 iOS 和 Android 的 React Native 中运行,但不适用于 React Native Web。我会提供更多代码。
-
@GalAbra 好的,编辑并添加了我的大部分代码结构。我省略了不相关的部分,但您应该能够从我发布的内容中大致了解我正在尝试做什么
-
我没有在参考中得到任何孩子。你能提供你的问题的展览演示吗
-
@CecilRodriguez ?
标签: javascript react-native react-native-web