我目前正在研究有关 React Native 的性能分析主题。我应该测量我们拥有的组件的渲染时间。我找到了以下方法来执行此操作,但不确定我的方法是否正确。
您可以在下面看到一个简单的按钮小部件。我在这里使用组件构造函数作为初始化函数来计算开始时间和 componentDidMount() 函数,它将在渲染/构建完成后调用以计算结束时间并将其打印出来。
import React, { Component } from "react";
import {
TouchableOpacity,
Text,
View,
StyleSheet
} from "react-native";
class ButtonWithBackground extends Component {
state = {
start:'0',
};
constructor(props) {
super(props);
this.state.start=Date.now();
}
componentDidMount() {
console.log('%c######## RENDER time ButtonWithBackground:','background: red',(Date.now()-this.state.start));
}
render() {
return (
<TouchableOpacity onPress={this.props.onPress}>
<View style={[styles.button, { backgroundColor: this.props.color }]}>
<Text>
press
</Text>
</View>
</TouchableOpacity>
);
}
}
const styles = StyleSheet.create({
button: {
backgroundColor: 'blue',
borderWidth: 1,
borderColor: 'blue',
borderRadius: 12,
padding: 8,
overflow: 'hidden',
fontWeight: "bold",
textAlign: "center",
fontSize: 28
}
});
export default ButtonWithBackground;
最佳答案
您可以使用 Reactotron Benchmarking而不是控制台日志
关于react-native - 组件测量渲染时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55783523/