如何通过React Native中的函数访问组件的引用?

时间:2019-05-27 10:05:29

标签: javascript react-native ref

我已经将自定义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 })

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

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

3 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

首先要确保MyComponent是一个组件而不是无状态的组件,然后要更改状态,请尝试以下方法:

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

当然,要使其正常工作,您的组件需要已经挂载,例如,如果您尝试在构造函数中调用它,它将无法正常工作

答案 2 :(得分:0)

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

SELECT * FROM results ORDER BY last_updated, popularity;

,请将ref参数更改为refs

componentDidMount() {
    this.props.refs(this) 
}

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