【问题标题】:How to access ref of a component through a function in React Native?如何通过 React Native 中的函数访问组件的 ref?
【发布时间】:2019-10-12 21:35:14
【问题描述】:

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

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

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

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

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

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

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

null is not an object (evaluating 'ref.setState')

其实我需要这个myFunction做的是,

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

状态myState 位于component 中,而我想通过screen 文件中的myFunction() 访问它。

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

【问题讨论】:

    标签: javascript react-native ref


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      首先确定 MyComponent 是一个组件,而不是一个无状态的组件,然后,要改变状态,试试这个:

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

      当然,要让它工作,你的组件需要已经挂载,如果你尝试在构造函数中调用它,它将无法工作

      【讨论】:

      • 对不起,没用。您能建议我另一种解决方案吗?
      • 我测试了它,它对我有用,我只是用不同的方法创建了 ref,我使用了 React.createRef()
      【解决方案3】:

      在您的组件内部,请在 componentDidMount 函数中添加

      componentDidMount() {
          this.props.refs(this) 
      }
      
      setState(key, value){
          this.setState({[key]:value})
      }
      

      请将 ref 参数更改为 refs

      <MyComponent refs={component => this.myComponent1 = component} />
      
      myFunction = (ref) => {
          ref.setState('myState', 'myValue')
      }
      

      【讨论】:

      • 对不起,没用。您能建议我另一种解决方案吗?
      猜你喜欢
      • 1970-01-01
      • 2020-02-24
      • 1970-01-01
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 2017-05-01
      • 1970-01-01
      • 2021-08-17
      相关资源
      最近更新 更多