Cec*_*uez 10 javascript react-native react-native-web
我在 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" } })
Run Code Online (Sandbox Code Playgroud)
这是基于此:
this.highlight = React.createRef();
Run Code Online (Sandbox Code Playgroud)
它作为道具传递到子组件中并用作:
<View ref={this.props.highlight}>
Run Code Online (Sandbox Code Playgroud)
它有几个孩子(也有嵌套的孩子)。
然而,在网络上,根本没有._children。
我如何访问儿童?
如果满足以下条件,则可以直接进行 DOM 操作Platform.OS === 'web':
let dom = ReactDOM.findDOMNode(this.highlight.current);
... DOM manipulations
Run Code Online (Sandbox Code Playgroud)
但如果不是绝对必要的话,这会让人感觉混乱和代码重复。我更愿意直接通过 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} />
);
}
}
Run Code Online (Sandbox Code Playgroud)
[编辑]:由于这个“某人的工作”是针对类组件的,因此这是我使用带有功能组件的动态引用的答案之一:带有功能组件的动态引用。它使用useRef()钩子来存储动态引用,因此可以使用特定的 id 在任何地方访问它们。
经过一段时间的尝试后,我找不到一种干净的方式来做你想做的事情。但是,正如您在 ReactDOM 中所说,有解决方案。我想到的另一件事是在你的孩子中设置你的裁判,然后将其传递给家长。
这是有人使用 key 属性在 .map 中进行“动态”引用,也许它对您有用:某人的工作
现在,使用直接操作不是一个好的做法,所以使用它而不是 ReactDOM.findDOMNode ...我真的不知道哪一个更糟糕,但我猜两者都很混乱。
| 归档时间: |
|
| 查看次数: |
1031 次 |
| 最近记录: |