在 React Native 中执行一个函数 OnRender

Perform a function OnRender in React Native

以下是生成一系列按钮的代码。当初始渲染发生时,一个函数确定元素是否有一个名为 init 的 prop。如果它这样做,它会执行操作,就好像该按钮已被单击一样。

从技术上讲,此代码有效,但它会触发警告,因为它会在渲染过程中有效触发重新渲染。如何触发有效的 OnRender 函数?

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>
     );
  }
}

警告是由于对仍在渲染的组件执行功能引起的,虽然技术上可行,但解决方案与问题一致。

有许多内置函数,包括满足有效 onRender 要求的函数。

从 render 中删除脚本并将其放在 componentDidMount() 函数内的 render 之上。

componentDidMount() {
        if(this.props.init){
            this.NavTabAction()
        }
    }

QED

对于基于 class 的 React 组件,例如在您的示例中,您将使用 componentDidMount() 生命周期方法,该方法仅在组件加载后触发一次,例如:

componentDidMount(){
  this.NavTabAction();
}

也就是说,我鼓励您使用 React Hooks,因为 React 世界正在从基于 class 的组件转向功能组件 + 挂钩。

要使用挂钩实现类似的 componentDidMount 功能,您可以在 functional 组件中像这样使用 useEffect

useEffect(() => {
  this.NavTabAction();
}, []);  // the [] is important here to behave similar to componentDidMount.