【问题标题】:How can I resolve Using this.refs is deprecated?如何解决使用 this.refs 已被弃用?
【发布时间】:2021-05-20 06:16:26
【问题描述】:

我知道 this.refs 已被弃用,可以使用 React.createRef 更改它,但在我的情况下是不同的

这是我们的代码

export default class ScrollableTabString extends Component {
    static ITEM_PADDING = 15;
    static defaultProps = {
        tabs: [],
        themeColor: '#ff8800',
    };
    static propTypes = {
        tabs: PropTypes.any,
        themeColor: PropTypes.string,
    };

    shouldComponentUpdate(nextProps, nextState) {
        if (nextProps.tabs !== this.props.tabs || this.state !== nextState) {
            return true;
        }
        return false;
    }

    constructor(props) {
        super(props);
        this.views = [];
        this.state = {};
        this.scrollableTabRef = React.createRef();
    }

    componentDidMount() {
        setTimeout(() => {
            this.select(this.props.defaultSelectTab ? this.props.defaultSelectTab : 0);
        }, 300);
    }

    select(i, code) {
        let key = 'tab ' + i;
        for (let view of this.views) {
            if (view) {
                let isSelected = false;
                if (view.key === key) {
                    isSelected = true;
                }
                // This refs is Object with many ref views
                if (this.refs[view.key]) {
                    this.refs[view.key].select(isSelected);
                }
                this.scrollableTabRef.current.goToIndex(i);
            }
        }
        if (this.props.onSelected) {
            this.props.onSelected(code);
        }
    }

    render() {
        this.views = [];

        if (this.props.tabs) {
            let tabs = this.props.tabs;
            for (let i = 0; i < tabs.length; i++) {
                if (tabs[i]) {
                    let key = 'tab ' + i;
                    let view = (
                        <TabItem
                            column={tabs.length}
                            themeColor={this.props.themeColor}
                            useTabVersion2={this.props.useTabVersion2}
                            isFirstItem={i === 0}
                            isLastItem={i === tabs.length - 1}
                            ref={key}
                            key={key}
                            tabName={tabs[i].name}
                            onPress={() => {
                                this.select(i, tabs[i].code);
                            }}
                        />
                    );
                    this.views.push(view);
                }
            }
        }
        let stypeTab = this.props.useTabVersion2
            ? null
            : { borderBottomWidth: 0.5, borderColor: '#8F8E94' };

        return (
            <ScrollableTab
                ref={this.scrollableTabRef}
                style={Platform.OS === 'ios' ? stypeTab : null}
                contentContainerStyle={Platform.OS === 'android' ? stypeTab : null}
            >
                {this.views}
            </ScrollableTab>
        );
    }
}

我想修复来自 eslint 的警告,但在我们的例子中,我不能使用 React.createRef

【问题讨论】:

  • 嗨@Anhdevit,您介意详细说明您的问题吗?我无法理解您想要实现什么或遇到了什么问题。谢谢。
  • 对不起@WingChoy 我更新了我的问题希望它更清楚
  • 1. createRef() 是否正常工作? 2. 你的应用中显示的 eslint 错误是什么? 3. 你能告诉我你正在归档的布局吗?
  • 这可能会对您有所帮助。 stackoverflow.com/a/54633947/9868549
  • 我可以知道您是否正在尝试制作具有不同内容的可滚动标签栏吗?

标签: reactjs react-native


【解决方案1】:

第一个解决方案

如果你的代码运行良好,只是想抑制 eslint 警告,

请将此行放在文件的第一行:(我相信您的 eslint 警告应该是 react/no-string-refs

/* eslint react/no-string-refs: 0 */

第二种解决方案

如果你的情况是你不能使用createRef(),那么尝试这样实现:

<ScrollableTab ref={(tab) => this.scrollableTab = tab} ...

然后这样调用:

this.scrollableTab?.goToIndex(index);

简化您的代码

阅读您的示例代码后,我建议您使用 state 而不是 string refs

由于您的示例中有很多冗余代码,我已尝试对其进行简化。

import React, { Component } from 'react';
import { Platform } from 'react-native';
import PropTypes from 'prop-types';

class ScrollableTabString extends Component {
    static ITEM_PADDING = 15;
    state = { activeTab: null }; scrollableTab;
    stypeTab = (!this.props.useTabVersion2 ? { borderBottomWidth: 0.5, borderColor: '#8F8E94' } : null);


    shouldComponentUpdate(nextProps, nextState) {
        return (nextProps.tabs !== this.props.tabs || this.state !== nextState);
    }

    componentDidMount() {
        this.setState({ activeTab: this.props.defaultSelectTab || 0 });
    }

    /* If your second param - code is optional, add default value */
    select = (index, code = null) => {
        let key = `tab ${index}`;

        /* Set activeTab state instead of calling function in every views */
        this.setState({ activeTab: key });
        
        this.scrollableTab?.goToIndex(index);
        /* Not sure what are you archiving, but why don't you use component state and pass the isSelected into item */
        /*for (let view of this.views) {
            if (view) {}
        }*/

        this.props.onSelected && this.props.onSelected(code);
    }

    renderTabs = () => {
        const { tabs, themeColor, useTabVersion2 } = this.props;

        return tabs?.map((tab, index) => {
            if (!tab) { return null; }

            return (
                <TabItem 
                    key={`tab ${index}`}
                    column={tabs.length} 
                    themeColor={themeColor} 
                    useTabVersion2={useTabVersion2}
                    isFirstItem={index === 0}
                    isLastItem={index === (tabs.length - 1)}
                    tabName={tab.name}
                    onPress={() => this.select(index, tab.code)}
                    isSelected={this.state.activeTab === `tab ${index}`}
                />
            );
        });
    };

    render() {
        return (
            <ScrollableTab
                ref={(tab) => this.scrollableTab = tab}
                style={Platform.OS === 'ios' ? stypeTab : null}
                contentContainerStyle={Platform.OS === 'android' ? stypeTab : null}
            >
                {this.renderTabs()}
            </ScrollableTab>
        );
    }
}

ScrollableTabString.defaultProps = {
    onSelected: null,  /* Miss this props */
    tabs: [],
    themeColor: '#ff8800',
    useTabVersion2: false    /* Miss this props */
};

ScrollableTabString.propTypes = {
    onSelected: PropTypes.func,  /* Miss this props */
    tabs: PropTypes.any,
    themeColor: PropTypes.string,
    useTabVersion2: PropTypes.bool  /* Miss this props */
};

export default ScrollableTabString;

更新 (18-02-2021)

select() 与 TabItem 一起使用可能会导致几个问题:

  • 性能问题(当用户按下一个 TabItem 时,select() 将被调用与 TabItem 数量一样多的次数,以更改内部的每个状态)
  • 由于过多的重复状态和引用,编码样式和维护成本不佳

我强烈建议在父组件中设置状态并将其作为道具传递给子组件。为了清楚地解释它是如何工作的,这里有一个最简单的示例:

ScrollableTabString.js

class ScrollableTabString extends Component {
  state = { activeTab: null };

  selectTab = (tabName) => { this.setState({ activeTab: tabName }); };

  renderTabs = () => this.props.tabs?.map((tab, index) => (
    <TabItem key={`tab ${index`} tabName={tab.name} onPress={this.selectTab} activeTab={this.state.activeTab} />
  ));
}

TabItem.js

class TabItem extends Component {
  /* Use this function on Touchable component for user to press */
  onTabPress = () => this.props.onPress(this.props.tabName);

  render() {
    const { activeTab, tabName } = this.props;
    const isThisTabActive = (activeTab === tabName);

    /* Use any props and functions you have to achieve UI, the UI will change according to parent state */
    return (
      <TouchableOpacity onPress={this.onTabPress} style={isThisTabActive ? styles.activeTab : styles.normalTab}>
        <Text>{tabName}</Text>
      </TouchableOpacity>
    );
  }
}

如果您确实需要在TabItem 中更改某些状态,请尝试在其中使用componentDidUpdate(),但它也应该是冗余代码:

componentDidUpdate(prevProps) {
  if (this.props.activeTab !== prevProps.activeTab) {
     // change your state here
  }
}

【讨论】:

  • 我同意第一个解决方案,但在我的代码中,这一行的问题 ``` // This refs is Object with many ref views if (this.refs[view.key]) { this. refs[view.key].select(isSelected); } ```
  • 嗨@Anhdevit,如果我错了,请纠正我。我认为当用户单击 scrollableTabString 内的 tabItem 时,您正在尝试设置 activeTab。如果是这种情况,我认为您应该尝试使用 state 来处理 activeTab 而不是循环 select() 函数中的值。请尝试我在答案中编写的示例代码,谢谢。
  • 我认为你是对的,但我的案例选择仍然正确,因为它设置了 TabItem 内的状态。我还能在 TabItem 中使用 select 功能吗?
  • 嗨@Anhdevit,每个 TabItem 中的状态实际上都连接到相同的数据。我已经对答案进行了一些更新,以便您更容易理解。如果您有任何理由必须使用 select(),请尝试通过完整示例提出另一个问题,谢谢 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-07
  • 2013-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多