如何通过 React Native 中的函数访问组件的 ref? [英] How to access ref of a component through a function in React Native?

查看:21
本文介绍了如何通过 React Native 中的函数访问组件的 ref?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将自定义 component 导入我的 screen 并在 render() 函数中呈现它.然后,为该自定义组件创建了一个 ref.现在,render() 函数看起来像这样.

I've imported a custom component into my screen and rendered it in the render() function. Then, created a ref to that custom component. Now, the render() function simply looks like this.

render() {
  return (
    <View>
      <MyComponent ref={component => this.myComponent1 = component} />
      <MyComponent ref={component => this.myComponent2 = component} />
      <MyComponent ref={component => this.myComponent3 = component} />
    </View>
  )
}

然后,在同一个 screen 文件中,我创建了另一个函数来访问我的自定义组件的状态.我是这样写的.

Then, In the same screen file, I've created another function to access the state of my custom component. I wrote it like this.

myFunction = (ref) => {
  ref.setState({ myState: myValue })
}

然后,我想像这样为那些单独的组件分别调用该函数.(在 screen 文件中)

Then, I want to call that function for those separate components separately like this. (In the screen file)

this.myFunction(this.myComponent1)
this.myFunction(this.myComponent2)
this.myFunction(this.myComponent3)

但是,它不起作用.它给了我以下错误.

But, it does not work. It gives me the following error.

null 不是对象(评估 'ref.setState')

实际上我需要这个 myFunction 来做的是,

Actually what I need this myFunction to do is,

this.myComponent1.setState({ myState: myValue })
this.myComponent2.setState({ myState: myValue })
this.myComponent3.setState({ myState: myValue })

状态 myStatecomponent 中,而我想通过 screen 中的 myFunction() 访问它代码>文件.

The state myState is in the component while I want to access it through the myFunction() in my screen file.

你能帮我解决这个问题吗?

Can you please help me to solve this problem?

推荐答案

这不是从父组件设置子组件的好习惯.我假设您想通过尝试这种方法为子组件的状态设置一些值.

This is not good practice to setState of child component from parent component. I am assuming you want to set some value to your child component's state by trying this approach.

您可以将这些值保留在本地状态并将其传递给 props,您的子组件将在那里重新渲染/获取更新的值.

You can keep these values in your local state and pass it to props and your child component will re-render / get updated value there.

class Component {
  constructor() {
    this.state = {
      myValues: {
        component1: "abc",
        component2: "xyz",
        component3: "123",
      }
    }
  }

  myFunction(componentName, newValue) {
    this.setState({
      myValues: {
        ...this.state.myValues,
        [componentName]: newValue
      }
    })
  }

  render() {
    return (
      <View>
        <MyComponent value={this.state.myValues.component1} />
        <MyComponent value={this.state.myValues.component2} />
        <MyComponent value={this.state.myValues.component3} />
      </View>
    )
  }
};

这篇关于如何通过 React Native 中的函数访问组件的 ref?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆