Javascript 无法设置属性';0';React本机ref中的null值

Javascript 无法设置属性';0';React本机ref中的null值,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我正在尝试设置一个React本机ref,如下所示,仅在类组件中: 这是我的密码: class DetailBody extends Component { constructor() { super(); this.myRefs = React.createRef([]); } clickText(index) { this.myRefs.current[index].setNativeProps({ style: { backgroundColor: '

我正在尝试设置一个React本机ref,如下所示,仅在类组件中:

这是我的密码:

class DetailBody extends Component {
  constructor() {
    super();
    this.myRefs = React.createRef([]);
  }

  clickText(index) {
    this.myRefs.current[index].setNativeProps({ style: { backgroundColor: '#FF0000' } });
  }

  render() {

    if (this.props.article.json.results.length === 0) {
      return <Loading />;
    }

    return (
      <View >
        <View>
          <View ref={this.props.highlight} nativeID="some-id" >
            {this.props.article.json.results.map((content, index) => (
              <TouchableOpacity onPress={() => this.clickText(index)}>
                <View key={index} ref={el => this.myRefs.current[index] = el}>{content}</View>
              </TouchableOpacity>
          </View>
        </View>
      </View>
类DetailBody扩展组件{
构造函数(){
超级();
this.myRefs=React.createRef([]);
}
单击文本(索引){
this.myRefs.current[index].setNativeProps({style:{backgroundColor:'#FF0000'}});
}
render(){
if(this.props.article.json.results.length==0){
返回;
}
返回(
{this.props.article.json.results.map((内容,索引)=>(
点击文本(索引)}>
this.myRefs.current[index]=el}>{content}
理论上,这应该让我在点击ref时添加背景色,就像我上面链接的零食一样

然而,我实际看到的是:

这似乎与我的ref中的.current为null有关,尽管传递了一个默认值


如何修复此错误?

如果ref回调被定义为一个内联函数,则在更新期间将调用它两次,首先使用null,然后使用DOM元素再次调用。

我还没有真正这样使用它,但我认为您可能只需要在构造函数中这样做:

this.myRefs = React.createRef();
this.myRefs.current = [];

你能提供
Detail.js
plz的代码吗?
current[index]
似乎是nullDetail.js很大,我看不出显示它的真正意义。问题是在这个特定的类中。如果我删除了ref,这个错误就不会发生。@ParthShah正在看零食,但是当前的[item.id]不应该也是null吗?
()=>点击文本(索引)
似乎是错误的。它可能是
()=>这个。点击文本(索引)
?这是最“反应”的吗这样做的方法还是有更好的方法?@CecilRodriguez这些文档都指向这一点,如果您希望更新以导致重新渲染,那么您实际上只需要它们处于状态,但在这种情况下,您只需要引用。我还看到一些人不使用
createRef
,只需执行
this.myRefs=[];