Function 在React Native中执行函数OnRender
下面是生成一系列按钮的代码。当初始渲染发生时,一个函数将确定元素是否具有名为init的属性。如果它这样做了,它将执行该操作,就像单击了该按钮一样 <>技术上,这个代码工作,但是它触发警告,因为它有效地在渲染中间触发重新渲染。如何触发有效的OnRender函数Function 在React Native中执行函数OnRender,function,react-native,render,Function,React Native,Render,下面是生成一系列按钮的代码。当初始渲染发生时,一个函数将确定元素是否具有名为init的属性。如果它这样做了,它将执行该操作,就像单击了该按钮一样 技术上,这个代码工作,但是它触发警告,因为它有效地在渲染中间触发重新渲染。如何触发有效的OnRender函数 export class NavTabItem extends React.Component { constructor(props) { super(props); global.register(t
export class NavTabItem extends React.Component {
constructor(props) {
super(props);
global.register(this, 'screen')
}
NavTabAction = () => {
global.setState({
screen: this.props.screen,
})
}
render() {
// determine whether the element has the prop of init and if it does click on it.
if(this.props.init){
this.NavTabAction()
}
return (
<TouchableOpacity onPress={this.NavTabAction}>
<View style={global.state.screen == this.props.screen ? [styles.NavTabItem, styles.NavTabItemSelected] : styles.NavTabItem}>
<View style={styles.NavTabIcon} />
<TextCap11 style={styles.NavTabLabel}>{this.props.children}</TextCap11>
</View>
</TouchableOpacity>
);
}
}
导出类NavTabItem扩展React.Component{
建造师(道具){
超级(道具);
全局注册表(此“屏幕”)
}
NavTabAction=()=>{
全局设置状态({
屏幕:这个。道具。屏幕,
})
}
render(){
//确定元素是否具有init属性,以及是否单击它。
if(this.props.init){
this.NavTabAction()
}
返回(
{this.props.children}
);
}
}
该警告是由于在仍在渲染的组件上执行某个功能而引起的,尽管该功能在技术上有效,但解决方案与问题相符
有许多内置函数,包括一个可以满足有效onRender要求的函数
从渲染中删除脚本,并将其放置在render inside componentDidMount()函数的上方
componentDidMount() {
if(this.props.init){
this.NavTabAction()
}
}
QED对于基于类的React组件,例如在您的示例中,您将使用lifecycle方法,该方法仅在加载组件后触发一次,例如:
componentDidMount(){
this.NavTabAction();
}
也就是说,我鼓励您使用React,因为React世界正在从基于类的组件转向功能组件+挂钩
要使用钩子实现类似的componentDidMount功能,您可以在功能组件中使用如下方法:
useEffect(() => {
this.NavTabAction();
}, []); // the [] is important here to behave similar to componentDidMount.
看起来值得进一步了解。复制useEffect会直接导致错误。我认为在使用它之前还有更多的东西需要学习吗?是的,您需要将组件重构为一个功能组件。文档中的第一个示例是一个很好的开始(如果需要在其他地方导入函数,请不要忘记导出该函数)。我强烈推荐阅读,但是,为了一个良好的基础。祝你好运